Question

I'm moving the JSON api of my Rails app to Node.js. I'm using Sequelize as the ORM to access my data in my postgres DB.

However, when I try to use the findOrCreate() and it needs to create an record, something weird happen:

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;

It seems it tries to create a record without any id and thus it throw the error

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

When it doesn't need to create a record (update or just read data) it works fine.

here is my code:

sequelize options

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

Model

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
  });
};

its associations:

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"})

and the code where I use 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
    })
})  

Can anybody help or point me in the right direction?

Thanks!

Was it helpful?

Solution

can you try this:

sequelize = new Sequelize('dashboard_development', 'dashboard', null, {
  dialect: "postgres",
  port:    5432,
  define: {
    underscored: true,
    timestamps: false
  },
  sync: { force: true },
  omitNull: true
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top