sequelize:一次插入记录集,而不是循环它们

问题描述:

我是新的在node.js中使用sequelize。sequelize:一次插入记录集,而不是循环它们

我有记录集,我插入记录使用.create()记录。

我认为必须有一种更直接的方式来一次性插入它们,而不是现在我正在循环它们在续集中。

这就是我现在所做的:

var myProcessTableSchema = { 
    Profile_UUID: {type:Sequelize.STRING(36), allowNull: false, primaryKey: true}, 
    ItemNmbr: {type:Sequelize.STRING(15), allowNull: true}, 
    UnitPrice: {type:Sequelize.DECIMAL(10,2), allowNull: true}, 
    ItemDesc: {type:Sequelize.STRING(512), allowNull: true}, 
}; 

var myProcessTableSchemaIndex = { 
    indexes: [ 
     { 
      name:'myProcess_profile', 
      unique:false, 
      fields:['Profile_UUID'] 
     } 
    ], 
    freezeTableName:true 
}; 

var myProcessTable = db.seqConnection.define(processingName, myProcessTableSchema, myProcessTableSchemaIndex); 
myProcessTable.sync({force: true, freezeTableName: true, createdAt: false, updatedAt: false}).then(function(){ 

     for (k = 0; k < recordsets[0].length; k++) 
     { 
      var logData = { 
        Profile_UUID: recordsets[0][k].Profile_UUID, 
        ItemNmbr: recordsets[0][k].ItemNmbr, 
        UnitPrice: recordsets[0][k].UnitPrice, 
        ItemDesc: recordsets[0][k].ItemDesc 
      };    

      myProcessTable.create(logData).then(function(){ 
       console.log('Inserted.'); 
      }).catch(function(err){ 
        console.log("MYSQL Create Processing Table Error : " + err.message);  
      }); 
     } 

     console.log('After loop....'); 
    }); 

只需使用Model.bulkCreate()其接受对象的数组,并把它们插入到数据库

User.bulkCreate([ 
    { username: 'barfooz', isAdmin: true }, 
    { username: 'foo', isAdmin: true }, 
    { username: 'bar', isAdmin: false } 
]) 

这里的文档http://docs.sequelizejs.com/en/latest/docs/instances/#working-in-bulk-creating-updating-and-destroying-multiple-rows-at-once