Sequelize findOrCreate()不会创建对象

时间:2013-12-17 11:06:37

标签: node.js postgresql orm sequelize.js

我正在将我的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 = 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
    })
})  

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

谢谢!

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

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