【问题标题】:Delete array element in document and save but it remains anyway (MongoDb using NodeJS)删除文档中的数组元素并保存,但它仍然存在(使用 NodeJS 的 MongoDb)
【发布时间】:2021-12-03 15:59:13
【问题描述】:

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

购物车架构

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.js mongodb mongoose


    【解决方案1】:

    稍微修改一下你的代码。

            //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 后您的本地数据已过时,因此调用save 将使用pull 之前的数据更新数据库,从而恢复删除项目。

    【讨论】:

    • 我复制了你的代码,但问题仍然存在 :( 刚刚遇到 * else * ``` await cart.products.pull ({productId}) // 删除了 ```消息Deleted item in cart. 返回但对象继续保留在数据库中
    • 这是我在 db.collection 中保留的结构:``` { "cart": [ { "_id": "6169a6232d14a04fa7f0cf38", "products": [ { "productId": “6169505bdfb4c919a9aa3ad8”, “量”:1, “_id”: “6169a6232d14a04fa7f0cf39”, “ID”: “6169a6232d14a04fa7f0cf39”}], “客户”: “616319ba22e85a00f2bba68d”, “__v”:0, “ID”: “6169a6232d14a04fa7f0cf38”} ] } ```
    • 我更改了代码。如果需要,请查看我上面的更新
    猜你喜欢
    • 2013-01-23
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2022-12-09
    • 1970-01-01
    相关资源
    最近更新 更多