Javascript 使用从mongodb获得的值填充数组后,将数组作为JSON响应发送
我试图将文档ID数组作为JSON响应发送,但作为响应获得的数组是空的。在将数组作为响应发送之前,如何确保该数组首先由文档Javascript 使用从mongodb获得的值填充数组后,将数组作为JSON响应发送,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,我试图将文档ID数组作为JSON响应发送,但作为响应获得的数组是空的。在将数组作为响应发送之前,如何确保该数组首先由文档IDs填充 exports.createItem = async (req,res,next) => { let itemsIds = []; req.body.forEach( async element => { let doc = await Item.findOneAndUpdate({ type: e
IDs
填充
exports.createItem = async (req,res,next) => {
let itemsIds = [];
req.body.forEach( async element => {
let doc = await Item.findOneAndUpdate({
type: element.type,
color: element.color,
size: element.size
}, {
$inc:{stock: element.stock}
}, {upsert:true, new: true});
itemsIds.push(doc._id);
});
res.status(200).json({
success: true,
itemsIds: itemsIds
})
}
我想确保
res.status(200).json({…})
方法仅在所有文档ID都被推送到mongo DB之后运行。现在,我只是在响应中得到itemsid
作为[]
。在发送响应之前,如何确保itemsIds数组首先由文档ID填充 forEach循环包含一个回调函数,我们不应该在其中使用async wait,而是使用for of循环来等待结果,将其推入数组,然后发送响应
exports.createItem = async (req,res,next) => {
let itemsIds = [];
req.body.forEach( async element => {
let doc = await Item.findOneAndUpdate({
type: element.type,
color: element.color,
size: element.size
}, {
$inc:{stock: element.stock}
}, {upsert:true, new: true});
itemsIds.push(doc._id);
});
res.status(200).json({
success: true,
itemsIds: itemsIds
})
}
exports.createItem = async (req,res,next) => {
let itemsIds = [];
for (var element of req.body) {
let doc = await Item.findOneAndUpdate({
type: element.type,
color: element.color,
size: element.size
}, {
$inc:{stock: element.stock}
}, {upsert:true, new: true});
itemsIds.push(doc._id);
}
res.status(200).json({
success: true,
itemsIds: itemsIds
})
}
@SagarChilukuri我已经更新了答案,请找到答案。它很有效!非常感谢。我会把这个答案标记为最佳答案,但你能解释一下为什么这个方法有效吗?为什么它使用for循环而不是forEach()工作?一旦你给forEach一个函数,它就把它当作一个异步调用,它不再由主线程处理,因此主线程开始在下一行工作,在你的例子中,它发送响应。