Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize bulkCreate() returns NULL value for primary key

I am writing rest using node, sequelize as ORM for mySQL. I am using bulkCreate function to create record in bulk. But in response it is returning null for primary key value.

Model

sequelize.define('category', {     cat_id:{         type:DataTypes.INTEGER,         field:'cat_id',         primaryKey: true,         autoIncrement: true,         unique:true     },     cat_name:{         type: DataTypes.STRING,         field: 'cat_name',         defaultValue:null     } }); 

Bulk Create operation :

var data = [         {             'cat_name':'fashion'         },         {             'cat_name':'food'         }     ];      orm.models.category.bulkCreate(data)     .then(function(response){         res.json(response);     })     .catch(function(error){         res.json(error);     }) 

response :

[   {     "cat_id": null,     "cat_name": "fashion",     "created_at": "2016-01-29T07:39:50.000Z",     "updated_at": "2016-01-29T07:39:50.000Z"   },   {     "cat_id": null,     "cat_name": "food",     "created_at": "2016-01-29T07:39:50.000Z",     "updated_at": "2016-01-29T07:39:50.000Z"   } ] 
like image 526
Sunil Sharma Avatar asked Jan 29 '16 07:01

Sunil Sharma


People also ask

What does Sequelize bulkCreate return?

Sequelize bulkCreate returns empty array.

How do I use bulkCreate in Sequelize?

Adding multiple rows at once using Sequelize bulkCreate() method. When you need to insert multiple rows to your SQL database table, you can use the Sequelize bulkCreate() method. The bulkCreate() method allows you to insert multiple records to your database table with a single function call.

How do I set NULL values in Sequelize?

update({ testCol: null }, { where: { id: id } }) . then((count) => { if (count) { return count; } }); should work. This works most of the time, depending on the global configuration of Sequelize you may still run into problems where it is not deleting null values.

How do I update bulk records in Sequelize?

While Sequelize doesn't provide a bulkUpdate() method, both update() and bulkCreate() methods allow you to update multiple rows with a single method. When you need to update multiple rows with different values, you can use the bulkCreate() method.


Video Answer


1 Answers

You should set the returning option:

Model.bulkCreate(values, {returning: true}) 
like image 130
Adam Avatar answered Sep 19 '22 20:09

Adam