如何编写 mongoDB 查询来更新集合中的对象数组?

问题描述 投票:0回答:1

我有一个购物车集合,它有两个字段:userId 和 products(这是与用户关联的所有产品的数组)。如果将具有相同 id 的产品添加到集合中,如何查询产品数组中的每个产品以更新其数量和总价?cart collection

这是我的代码。因此,当我尝试使用邮递员对此进行测试时,它实际上会更新产品的数量和总价,其中 id 匹配,但仅更新一次。但这个结果不会保留在数据库中,即,当我在终端上运行 db.cart.find() 时,我看不到更新。

exports.addCartItem = catchAsync(async (req, res, next) => {
    const product = req.body.product;
    const userId = req.user._id;

    let cart = await Cart.findOne( {userId} ).exec();
    console.log(cart)
    
    const price = product.price;
    const title = product.title;
    const quantity = product.quantity;
    const totalPrice = product.totalPrice;
    const status = product.status;

    if (cart) {
        const itemIndex = cart.products.findIndex((p) => p.product.toString() === product.product);  
        console.log(itemIndex)
        if(itemIndex > -1) {
            let productItem = cart.products[itemIndex];
            productItem.quantity += quantity;
            productItem.totalPrice = productItem.quantity * price;
            cart.products[itemIndex] = productItem;
        } else {
            cart.products.push(
                { 
                    product: product.product, 
                    title, quantity, price, 
                    status, 
                    totalPrice: quantity * price,
                });  
        }

        res.status(200).json(cart);
    
    } else {
        const newCart = await Cart.create({
            userId,
            products: [
                { 
                    product: product.product, 
                    title, 
                    quantity, 
                    price, 
                    status, 
                    totalPrice: quantity * price 
                }],
        });
        if (!newCart) next(AppError('Product was not created', 400))
        return res.status(201).json({
            status: 'success',
            newCart
        });
    }
});```
node.js mongodb express mongodb-query javascript-objects
1个回答
0
投票

要更新 MongoDB 集合中的对象数组,可以使用 $set 运算符和位置运算符 $ 来指定要更新的数组元素。以下是您可以修改代码以更新购物车集合中的产品数组的方法:

exports.addCartItem = catchAsync(async (req, res, next) => {
const product = req.body.product;
const userId = req.user._id;

let cart = await Cart.findOne({ userId }).exec();
console.log(cart)

const price = product.price;
const title = product.title;
const quantity = product.quantity;
const totalPrice = product.totalPrice;
const status = product.status;

if (cart) {
    const itemIndex = cart.products.findIndex((p) => p.product.toString() === product.product);
    console.log(itemIndex)
    if (itemIndex > -1) {
        // Update an existing product in the products array
        cart.products[itemIndex].quantity += quantity;
        cart.products[itemIndex].totalPrice = cart.products[itemIndex].quantity * price;
    } else {
        // Add a new product to the products array
        cart.products.push(
            {
                product: product.product,
                title,
                quantity,
                price,
                status,
                totalPrice: quantity * price,
            });
    }

    // Update the cart document in the database
    await cart.save();

    res.status(200).json(cart);

} else {
    // Create a new cart document with the product
    const newCart = await Cart.create({
        userId,
        products: [
            {
                product: product.product,
                title,
                quantity,
                price,
                status,
                totalPrice: quantity * price
            }],
    });

    if (!newCart) next(AppError('Product was not created', 400))

    res.status(201).json({
        status: 'success',
        newCart
    });
}

}); 在此代码中,对 cart.products 数组进行更改后,我们调用 wait cart.save() 将更改保存到 MongoDB 数据库。这将使用修改后的产品数组更新购物车文档。

© www.soinside.com 2019 - 2024. All rights reserved.