'null value in column "id" of relation "messages" violates not-null constraint
When nodejs 14.x/sequelize 6.5.x save a message, it throws an strange error:
Error in saving/braodcasting a new message DatabaseError [SequelizeDatabaseError]: null value in column "id" of relation "messages" violates not-null constraint
Here is the table structure of message:
Here is the instance of message to be saved:
let msg = Message.build();
msg.sender_id = req.viewer.id;
msg.room_id = room_id;
msg.type = type;
msg.set("data.msg_body", req.body.data.msg_body);
console.log("new message post msg : ", msg);
await msg.save(); //<<== throws error about null id
Since column id can not be null and the id was assigned during msg.save(), what the error is really complaining about and how to fix it?
Here is the model def:
const { DataTypes, Model } = require('sequelize');
const Op = DataTypes.Op;
const db = require("../startup/db");
const Joi = require('joi');
class Message extends Model {};
Message.init({
room_id: {type: DataTypes.STRING, //[s,t]idfort-token(seller or poster's)]
allowNull:false,
},
sender_id: {type: DataTypes.INTEGER,
allowNull:false,
validate: {
isInt:true,
},
},
type:{
type:DataTypes.STRING,
},
receiver_id : {type: DataTypes.INTEGER},
data: {
type: DataTypes.JSONB,
validate: {
validateJSONData(value) {
let counter = 0;
for (key in value) {
if (value[key] !== null) {
++counter;
}
};
if ( counter === 0) {
throw new Error('Empty message!');
};
}
}
},
createdAt: DataTypes.DATE,
}, {
sequelize:db,
modelName: 'message',
timestamps:true,
updatedAt: false,
indexes: [
{
fields: ['room_id']
}, {
fields: ['sender_id']
}, {
fields : ['receiver_id']
} , {
fields : ["type"]
}
]
});
module.exports.Message = Message;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

