gpt4 book ai didi

node.js - Sequelize : Inserting recordsets in one go instead of looping them

转载 作者:行者123 更新时间:2023-12-03 22:23:54 24 4
gpt4 key购买 nike

我是在 node.js 中使用 sequelize 的新手。

我有一个记录集,我正在使用 .create() 按记录插入记录。

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

这就是我现在正在做的:

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 文档

关于node.js - Sequelize : Inserting recordsets in one go instead of looping them,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38972162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com