【发布时间】:2018-09-16 01:06:04
【问题描述】:
这让我发疯了,我花了好几个小时把头发拉出来——经典。我正在从 API 端点接收数据。我正在遍历数据并需要在多个表中创建多个记录,并且需要使用第一个创建记录的最后插入的 id。但我没有得到正确的结果:
请求代码:
request(options, (err, res, body) => {
if (err) { return console.log(err); }
for (var i = 0; i < body.length; i++) {
var contact = {
name: body[i].person.first_name + " " + body[i].person.last_name
};
var article = {
name: body[i].article.name,
author: null // want this to be last inserted id of contact, after it's saved.
};
var note = {
text: body[i].person.first_name+" wrote an article.",
contactId: null // want this to be last inserted id of contact, after it's saved.
};
Contact.create(contact).then(function (result) {
console.log(result.id);
note.contactId = result.id;
article.author = result.id;
Article.create(article).then();
Note.create(note.then();
});
}
}
结果是联系人被保存,但其余部分未保存。我的 JS 排骨不是很好,所以我认为我遇到了异步问题或者可能缺乏技能,但是我四处搜索并没有找到循环模型创建的示例。
请你帮我回到正确的道路上吗?
【问题讨论】:
标签: javascript node.js sequelize.js