Sequelize bulkCreate() returns NULL value for primary key

Sunil Sharma picture Sunil Sharma · Jan 29, 2016 · Viewed 42.2k times · Source

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

Answer

Adam picture Adam · Jan 29, 2016

You should set the returning option:

Model.bulkCreate(values, {returning: true})