为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用猫鼬更新 MongoDB 中的数组?

如何使用猫鼬更新 MongoDB 中的数组?

温温酱 2022-05-26 14:22:36
我有两个模式,用户和产品。用户模式是我存储所有产品 ID 和用户添加到购物车的商品数量的地方。当用户向“/checkout”发出请求时,它应该更新数量,然后将其从购物车中删除。我在结帐时遇到问题没有更新数量。router.post('/checkout', auth, catchAsync(async (req, res) => {    const user = await User.findById(req.session.userId);    const err = [];    if (user && user.products.length > 0) {        user.products.map(async (product) => {            let total = 0;            const p = await Product.findById(product.productID);            if (p.quantity > 0 && p.quantity > product.quantity) {                console.log('IN');                total = p.quantity - product.quantity;                console.log(total);                await Product.findOneAndUpdate({ _id: product.productID }, { $set: { quantity: total } });            } else {                err.push(`Item, ${p.name} is sold out`);            }        });        await User.findOneAndUpdate({ _id: req.session.userId }, { $set: { products: [] } });        if (err.length) {            return res.status(500).json({ message: err });        }        return res.status(200).json({ message: 'OK' });    }    return res.status(200).json({ message: 'Empty cart' });}));用户架构:产品架构:
查看完整描述

1 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

我相信您的代码中的问题出在user.products.map(...)函数上,因为您永远不会等待您在地图中创建的所有承诺都得到解决。


换句话说,该map函数返回一个待处理的 Promise 数组,但它不会等待它们完成,因此执行会继续执行,直到到达res.status(...)任何代码map执行之前的其余代码。


你有不同的选择来解决它,但主要是你需要处理map函数返回的承诺数组并等待它们完成,然后再结束你的代码。async/await在Google Developers Web 基础指南中有一个很好的解释如何处理这种情况。


我通常利用Promise.all()函数,它从承诺数组中返回一个承诺,因此您可以等到代码中的代码为数组中的每个项目并行map执行(即在您的情况下)。您可以在MDN 文档中阅读更多相关信息。product


// ...


let promisesArray = user.products.map(async product => {...});

// promisesArray should look like: [Promise { <pending> }, Promise { <pending> }, … ]


// Using Promise.all we wait for each of them to be done in parallel

await Promise.all(promisesArray);


// Now you are certain the code in the map has been executed for each product


// ...

一个好的做法是使用try {} catch(err) {}块Promise.all()来处理某些承诺被拒绝的情况


查看完整回答
反对 回复 2022-05-26
  • 1 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号