Here is my model for sample
const Sequelize = require('sequelize')
const db = require('../DBconfig')
const SampleModel = db.define('sample',{
id:{
type: Sequelize.INTEGER,
primaryKey:true,
autoIncrement:true,
},
name:{
type: Sequelize.STRING,
allowNull:true
}
},{freezeTableName:true})
module.exports = SampleModel;
Here is a simple get request where I have just passed a name value to it.
router.get('/sample',( req ,res)=>{
const newSample = SampleModel.build({
name:"User123"
})
console.log(newSample)
})
Now here is the output when I run this... the id field is null
Executing (default): SELECT 1 1 AS result sample { dataValues: { id: null, name: 'User123' }, _previousDataValues: { name: undefined }, _changed: Set { 'name' }, _options: { isNewRecord: true, _schema: null, _schemaDelimiter: '' }, isNewRecord: true}
CodePudding user response:
There are a couple of things going on here.
Sequelize should create an id column by default. I don't believe that you need to explicitly define this in your model.
You are using the Model.build() method, which creates a new object instance of the model, but does not actually interact with the database yet. If you call the .save() method on the instance, it will commit the instance to the database, which is when the id should be generated.
edit to add: newSample.save() will not make any changes to the newSample object. In order to get an instance with the id included, you'll need to get the returned value from .save()
const savedSample = await newSample.save()