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

guz6ccqo  于 2023-10-16  发布在  Go
关注(0)|答案(1)|浏览(107)

我有一个购物车集合,它有两个字段,userId和products(它是与用户关联的所有产品的数组)。如果有一个id相同的产品添加到集合中,我如何查询products数组中的每个产品以更新其数量和总价?cart collection
这是我的代码。因此,当我尝试使用postman测试时,它实际上更新了产品的数量和总价,其中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
        });
    }
});```
wrrgggsh

wrrgggsh1#

要更新MongoDB集合中的对象数组,可以使用$set运算符沿着位置运算符$来指定要更新的数组元素。下面介绍如何修改代码以更新Cart集合中的products数组:

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数组进行更改后,我们调用await cart.save()将更改持久化到MongoDB数据库。这将使用修改后的产品数组更新Cart文档。

相关问题