gpt4 book ai didi

node.js - Sequelize findOrCreate() 不创建对象

转载 作者:行者123 更新时间:2023-11-29 12:13:09 24 4
gpt4 key购买 nike

我正在将我的 Rails 应用程序的 JSON API 迁移到 Node.js。我正在使用 Sequelize作为 ORM 访问我的 postgres 数据库中的数据。

但是,当我尝试使用 findOrCreate() 并且它需要创建一条记录时,发生了一些奇怪的事情:

INSERT INTO "gameweeks" ("id","number","gw_pts","transfers","transfers_malus","team_id","captain_id","vice_captain_id","in_bank","team_value","overall_rank") VALUES (NULL,16,NULL,NULL,NULL,6,NULL,NULL,NULL,NULL,NULL) RETURNING *;
Executing (default): SELECT * FROM "gameweeks" WHERE "gameweeks"."team_id"=12 AND "gameweeks"."number"=16 LIMIT 1;

它似乎试图创建一个没有任何 id 的记录,因此它抛出了错误

error: null value in column "id" violates not-null constraint

当它不需要创建记录(更新或只读取数据)时它工作正常。

这是我的代码:

Sequelize 选项

sequelize = new Sequelize('dashboard_development', 'dashboard', null, {
dialect: "postgres",
port: 5432,
define: {
underscored: true,
timestamps: false
},
sync: { force: true }
})

型号

gameweek.js:

module.exports = function(sequelize, DataTypes) {
return sequelize.define('gameweek', {
number: DataTypes.INTEGER,
gw_pts: DataTypes.INTEGER,
transfers: DataTypes.INTEGER,
transfers_malus: DataTypes.INTEGER,
team_id: DataTypes.INTEGER,
captain_id: DataTypes.INTEGER,
vice_captain_id: DataTypes.INTEGER,
in_bank: DataTypes.FLOAT,
team_value: DataTypes.FLOAT,
overall_rank: DataTypes.INTEGER
});
};

它的关联:

global.db.Gameweek.belongsTo(global.db.Team)
.hasMany(global.db.Player, {as: "substitutes", joinTableName: "gameweeks_substitutes"})
.hasMany(global.db.Player, {joinTableName: "gameweeks_players"})
.belongsTo(global.db.Player, {as: "captain", foreignKey: "captain_id"})
.belongsTo(global.db.Player, {as: "vice_captain", foreignKey: "vice_captain_id"})

以及我使用 findOrCreate 的代码:

db.Team.find({where: {fpl_id: fplTeamId}}).complete(function (err, team){
if (err) throw err;
db.Gameweek.findOrCreate({team_id: team.id, number: gwNumber}).complete(function (err, gameweek, created) {
if (err) throw err;
// Do stuff with the returned gameweek
})
})

任何人都可以帮助或指出正确的方向吗?

谢谢!

最佳答案

你能试试这个吗:

sequelize = new Sequelize('dashboard_development', 'dashboard', null, {
dialect: "postgres",
port: 5432,
define: {
underscored: true,
timestamps: false
},
sync: { force: true },
omitNull: true
})

关于node.js - Sequelize findOrCreate() 不创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20632497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com