首页 > 解决方案 > 删除文档中的数组元素并保存,但它仍然存在(使用 NodeJS 的 MongoDb)

问题描述

我有一个购物车。在模式的当前状态下,其中包含的每个元素都由 Products 数组中的一个对象表示。对该函数的每次调用都会删除等于 1 的通过其 itemId 传递的对象的数量。当我想删除数量等于 1 的对象(因此数量值达到 0)时,我想从 Products 数组中删除购物车中的对象(因此 itemId 和数量)。如果大于 1,则只有减少数量值时才起作用,而不是在消除产品编号时,消息“已删除购物车中的商品。但事实并非如此,它仍然保留在数据库中

购物车架构

const mongoose = require('mongoose');
const idValidator = require('mongoose-id-validator');

const Schema = mongoose.Schema;
 

const cartSchema = new Schema ({
    products: [
        {
            productId: { type: mongoose.Types.ObjectId, required: true, ref: 'Product' },
            quantity: { type: Number, required: true },
        }
    ],
    customer: { type: mongoose.Types.ObjectId, required: true, unique: true, ref: 'User'}
});


cartSchema.plugin(idValidator);
module.exports = mongoose.model('Cart', cartSchema);

减少功能

const removeToCartByUserId = async (req, res, next) => {
    const userId = req.params.uid; 
    const { productId } = req.body;
    const quantity = 1;
    try {
        let cart = await Cart.findOne({customer: userId});

        //Cart exist for user
        if(cart) {
            let itemIndex = cart.products.findIndex(p => p.productId == productId);

            //product exists in the cart, update the quantity
            if (itemIndex > -1) {
                let productItem = cart.products[itemIndex];
                if(productItem.quantity > 1) {
                    productItem.quantity -= quantity;
                    cart = await cart.save();
                    res.status(201).json({ cart });
                } else { // delete product in array
                    await cart.products.pull({ productId: productId }) // removed
                    cart = await cart.save();
                    res.status(200).json({ message: 'Deleted item in cart.' });
                }
            } 
        } else { // no Cart for the user, exit
            const error = new HttpError('Something went wrong with the cart.', 500);
            return next(error); 
        }
    } catch(err) {
        console.log(err);
        const error = new HttpError('Something went wrong with the cart.', 500);
        return next(error); 
    }
};

更新:我编辑了代码,现在它可以工作了

 //product exists in the cart, update the quantity
if (itemIndex > -1) {
    let productItem = cart.products[itemIndex];
    productItem.quantity -= quantity;
    if(productItem.quantity > 0) {
        cart = await cart.save();
        res.status(201).json({ cart });
    } else { // delete product in array
        await Cart.updateOne(
            { itemIndex },
            {$pull : { "products": { productId } } }
            );

        res.status(200).json({ message: 'Deleted item in cart.' });
    }
}

标签: node.jsmongodbmongoose

解决方案


稍微改变你的代码。

        //product exists in the cart, update the quantity
        if (itemIndex > -1) {
            let productItem = cart.products[itemIndex];
            productItem.quantity -= quantity;
            if(productItem.quantity > 1) {
                cart = await cart.save();
                res.status(201).json({ cart });
            } else { // delete product in array
                await cart.products.pull({ productId }) // removed

                res.status(200).json({ message: 'Deleted item in cart.' });
            }
        }

您需要在应该调用if该语句之前降低产品质量。else

另外,我已经删除了cart.save调用,这可能是因为您的本地数据在调用后已过时,pull因此调用 asave将使用您之前拥有的数据更新数据库,pull从而恢复删除项目。


推荐阅读