首页 > 解决方案 > 为 mongodb 中的现有值添加价值

问题描述

我有一个

{
"name": "Banana",
"quantity": 5
} 

在“产品”数据库中。我需要的是在“数量”中添加(例如)200,因此“数量”最后将是 205。我是 MongoDB 和猫鼬的新手。我试过了

const result = await Product.updateOne({ 
       'name' : req.params.name 
    },
    {
        $set: {
            quantity: this.quantity+req.body.quantity
        }
    }
)

但它没有用。任何帮助表示赞赏

标签: javascriptnode.jsmongodbmongoose

解决方案


尝试使用$inc运算符:

const result = await Product.updateOne({ 
    'name' : req.params.name 
},
{
    $inc: {
        quantity: req.body.quantity
    }
})

推荐阅读