【发布时间】:2021-02-02 12:03:41
【问题描述】:
当我检索一个 json 文档时,我想更新一个邀请数组。该数组由 _id 值组成,我想更新并设置为用户名。为此,我查找 _id 并找到相应的用户名。然而,array.push 函数在查找相应的用户名之前完成。因此添加了一个空值。找到对应的用户名后,如何让节点等待推送。
exports.contactBoard = (req, res) => {
const username = req.params.username;
contactUsername = '';
User.findOne({
'username': username
}).then(document => {
document.invitationsFromFriends.forEach(element => {
User.findById(element).then(document => {
contactUsername = document.username;
console.log("locatie 1" + contactUsername)
})
})
console.log("locatie 2" + contactUsername)
document.invitationsFromFriends.push(contactUsername);
res.status(200).json({
message: "retrieved user contacts",
contacts: document
})
})
}
【问题讨论】:
-
只需将
res.status(200).json(....)调用移到User.findById()的.then()函数内即可。
标签: node.js asynchronous