【问题标题】:How to increment a field inside the array of documents in mongo Db?如何在 mongo Db 的文档数组中增加一个字段?
【发布时间】:2021-09-30 19:18:24
【问题描述】:

当 productId 与 itemid 匹配时,我想增加购物车的 products 数组中的数量字段。我也想获得更新的文档作为回报。

这是我的购物车模型

import mongoose from 'mongoose';

const cartSchema = new mongoose.Schema({
    userId: {
        type: String,
        required: true,
    },
    products: [
        {
            productId: {
                type: String,
            },
            quantity: {
                type: Number,
                default: 1
            }
        }

    ]
    
}, {timestamps: true});
const Cart = new mongoose.model('Cart', cartSchema);

export default Cart;

这就是我正在做的事情:

const updatedCart = await Cart.findOneAndUpdate({"products.productId": itemid}, {$inc: {quantity: 1}}, {new: true})

//console.log(updatedCart)

但是一个空数组返回并且数量没有增加。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    根据您的架构,没有 quantity 字段。因此,您的 mongoose 操作 不会更新任何文档。

    因此它不会返回任何文档,因为new: true 只返回更新后的文档。

    [options.returnOriginal=null] «Boolean» 新选项的别名。 returnOriginal: false 等价于new: true


    您可以使用positional $ operator 更新products 数组中过滤后的productquantity

    位置 $ 运算符标识数组中要更新的元素,而无需明确指定该元素在数组中的位置。

    const updatedCart = await Cart.findOneAndUpdate({ "products.productId": itemid },
      { $inc: { "products.$.quantity": 1 } }, 
      { new: true });
    

    Sample Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 2011-11-04
      • 2014-10-04
      • 2015-01-10
      • 2018-04-27
      • 2021-11-15
      • 2015-07-28
      相关资源
      最近更新 更多