Sequelize bulkCreate() returns NULL value for primary key

前端 未结 7 1616
孤城傲影
孤城傲影 2020-12-15 04:46

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

相关标签:
7条回答
  • 2020-12-15 04:58

    From the documentation: please notice that these may not completely represent the state of the rows in the DB. This is because MySQL and SQLite do not make it easy to obtain back automatically generated IDs and other default values in a way that can be mapped to multiple records. To obtain Instances for the newly created values, you will need to query for them again. http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-bulkCreate

    But you can pass an option to make it return the id

    orm.models.category.bulkCreate(data, { returning: true })
    
    0 讨论(0)
  • 2020-12-15 05:01

    You should set the returning option:

    Model.bulkCreate(values, {returning: true})
    
    0 讨论(0)
  • 2020-12-15 05:02
    var data = [
        {
            'cat_name':'fashion'
        },
        {
            'cat_name':'food'
        }
    ];
    
    Model.bulkCreate(data)
    .then(function() {
    
     //(if you try to immediately return the Model after bulkCreate, the ids may all show up as 'null')
      return Model.findAll()
    })
    .then(function(response){
        res.json(response);
    })
    .catch(function(error){
        res.json(error);
    })
    
    0 讨论(0)
  • 2020-12-15 05:04
    var data = [{
       'cat_name':'fashion'
      },
      {
       'cat_name':'food'
      }
     ];
    
    orm.models.category.bulkCreate(data,{individualHooks: true})
     .then(function(response){
       res.json(response);
     })
     .catch(function(error){
       res.json(error);
     });
    
    0 讨论(0)
  • 2020-12-15 05:10

    Tested in MySQL:

    Model.bulkCreate(values, { individualHooks: true })
    
    0 讨论(0)
  • 2020-12-15 05:15

    Unfortunately that doesn't work in the latest version. They explain why here: http://sequelize.readthedocs.org/en/latest/api/model/#bulkcreaterecords-options-promisearrayinstance

    note that the description specifically mentions mysql. You'll have to query for them. (example includes var _ = require('lodash');

    var cat = rm.models.category;
    cat.bulkCreate(data)
     .then(function (instances) {
        var names = _.map(instances, function (inst) {
          return inst.cat_name;
        });
        return cat.findAll({where: {cat_name: {$in: names}}); 
     })
     .then(function(response){
        res.json(response);
     })
     .catch(function(error){
        res.json(error);
     });
    
    0 讨论(0)
提交回复
热议问题