英文:
How to execute find all method after executing for loop in Sequelize Node.Js?
问题
我有一个for循环。然后我将每个值插入到表中。之后,当我使用findAll/findOne方法进行查询时,它显示为null。我想在执行for循环后获取User_Paper表的数据。
const newPaper = new Paper({
// ...其他属性
});
newPaper.save().then(new_paper=> {
for (let i = 0; i < new_paper.contributor.length; i++) {
const newUser_Paper = new User_Paper({
userId: null,
username: new_paper.contributor[i],
paperId: new_paper.id,
});
newUser_Paper.save();
}
User_paper.findOne({
where: {
username: : Touhid,
paperId: new_paper.paperId
}
}).then(x=>{
console.log(x);
});
});
之后输出显示为null。我想在执行for循环后获取User_Paper表的数据。这是我的两张表。请帮我解决。
英文:
I have a for loop. And I inserted each value into a table. After that when I query using findAll/findOne method, it says null. I want to get the data of User_Paper table after executing for loop.
const newPaper = new Paper({
title,
abstract,
contributor,
contributor: authors,
paper_file: file,
paper_topicId: ptopic.id,
categoryId: c1.id,
postingDate,
postingTime
});
newPaper.save().then(new_paper=> {
for (let i = 0; i < new_paper.contributor.length; i++) {
const newUser_Paper = new User_Paper({
userId: null,
username: new_paper.contributor[i],
paperId: new_paper.id,
});
newUser_Paper.save()
}
User_paper.findOne({
where: {
username: : Touhid,
paperId: new_paper.paperId
}
}).then(x=>{
console.log(x)
})
})
After that the output is showing null. I want to get the data of User_Paper table after executing for loop.
This is my two table. Please Help me out.
PaperUser_Paper
答案1
得分: 0
你得到null
的原因是因为你没有等待for
循环中创建的User_Paper
对象保存完成。在查询之前,你需要在每个对象上调用save()
方法。
newUser_Paper.save().then(() => {
// 现在你可以查询 User_Paper 对象了
User_paper.findOne({
where: {
username: :Touhid,
paperId: new_paper.paperId
}
}).then(x => {
console.log(x);
});
});
英文:
The reason why you are getting null
is that you are not waiting for the save of the User_Paper
objects that you are creating in the for
loop. You need to call save() on each of those objects before you can query for them.
newUser_Paper.save().then(() => {
// Now you can query for the User_Paper objects
User_paper.findOne({
where: {
username: :Touhid,
paperId: new_paper.paperId
}
}).then(x => {
console.log(x);
});
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论