gpt4 book ai didi

javascript - 在用从 mongodb 获得的值填充数组后,将数组作为 JSON 响应发送

转载 作者:行者123 更新时间:2023-11-30 13:54:56 24 4
gpt4 key购买 nike

我正在尝试发送一个文档 ID 数组作为 JSON 响应,但我作为响应获得的数组是空的。在作为响应发送之前,如何确保数组首先由文档 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 数据库后运行。现在,我只是在响应中将 itemsIds 作为 [ ] 获取。在发送响应之前,如何确保 itemsIds 数组首先由文档 ID 填充?

最佳答案

forEach 循环包含一个回调函数,这里我们不应该使用async await,使用for of 循环来等待结果,将它压入数组然后发送响应。

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
})
}

关于javascript - 在用从 mongodb 获得的值填充数组后,将数组作为 JSON 响应发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57494833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com