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

我有两个模式,用户和产品。用户模式是我存储所有产品 ID 和用户添加到购物车的商品数量的地方。

http://img.mukewang.com/628f1cbe00013ca804170173.jpg

当用户向“/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' });

}));


用户架构:

http://img2.mukewang.com/628f1ccf000138c104990943.jpg

产品架构:

http://img2.mukewang.com/628f1ce000018dc705330717.jpg


温温酱
浏览 111回答 1
1回答

莫回无

我相信您的代码中的问题出在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 parallelawait Promise.all(promisesArray);// Now you are certain the code in the map has been executed for each product// ...一个好的做法是使用try {} catch(err) {}块Promise.all()来处理某些承诺被拒绝的情况
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript