[英]Sequelize - Bulk create from array
I have an array of items and need to create them to DB. 我有一个项目数组,需要创建它们到DB。
I need to check each insert if it success so insert to new array (results) the item + success = true as a json. 我需要检查每个插入是否成功,因此插入新数组(结果)项目+ success = true作为json。
If not succeed to create - insert to the same array before (results) the item + success = false. 如果没有成功创建 - 在(结果)项目+ success = false之前插入到同一个数组。
Here's the code: 这是代码:
create_cards: function (filter_id, is_filter, cards) {
var result = [];
var curr_card = null;
for (var card in cards) {
curr_card = this.create( {
filter_id: filter_id,
template: card.template,
state: card.state,
question_id: card.question_id || -1,
answers: card.answers || -1,
description: card.description || -1,
correct_answer: card.correct_answer || -1
}).then(function(card) {
result.push({card: JSON.stringify(card.dataValues), success: true})
},function(err) {
result.push({card: card.dataValues, success: false})
});
}
return results;
}
Now, 2 questions: 现在,2个问题:
There is 'return result' after the loop is over, but i get empty array.. How should i do bulk create AND after each create, to make sure if the creation succeed? 循环结束后有'返回结果',但是我得到空数组。我应该如何在每次创建后批量创建AND,以确保创建成功?
How should i get the card in the error function? 我该如何在错误功能中获得卡? i get only 'err' as variable to the reject function.
我只将'err'作为拒绝函数的变量。
Thanks! 谢谢!
create_cards: function(filter_id, is_filter, cards) { var result = []; var promises = cards.map(function(card) { return this.create({ filter_id: filter_id, template: card.template, state: card.state, question_id: card.question_id || -1, answers: card.answers || -1, description: card.description || -1, correct_answer: card.correct_answer || -1 }) .then(function() { result.push({ card: card, success: true }); }) .catch(function(err) { result.push({ card: card, success: false }); return Promise.resolve(); }); }); return Promise.all(promises) .then(function() { return Promise.resolve(result); }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.