Mongodb更新声明:如何更新json对象?

时间:2017-07-17 07:18:26

标签: json node.js mongodb express

我的目标是这样的:

[
{
    "_id": "596b088131ea400490897c50",
    "stocks": [
        {
            "product": "596b083831ea400490897c4d",
            "price": 45,
            "stock": 18,
            "limit": 4,
            "_id": "596b088331ea400490897c59"
        },
        {
            "product": "596b082931ea400490897c49",
            "price": 49,
            "stock": 20,
            "limit": 18,
            "_id": "596b088331ea400490897c58"
        }
    ]
}
]

我想现在价格为10,即45。所以,我正在使用

Store.update ({_id: storeId}, {'$set':"stocks.j.price":req.body.price});

其中j是用于循环数组库存中不同产品的变量,价格正在请求体中发送。但它似乎没有更新数据库。有人可以解释我该怎么做?

修改 我终于找到了解决方案。

var {id} = req.params;

id = ObjectId(id);
//console.log(typeof Store);
// const something = _.filter(Store, req.body.stores);
// console.log(something);
Store.find({
    _id: {
        $in : req.body.stores
    }
}, (err,data)=>{
    if(!err){
        for (var i=0; i<data.length; i++){

            var index = _.findIndex(data[i].stocks, {'product' : id});
            console.log(typeof data[i].id);
            var tempId = ObjectId(data[i].id);
            var setModifier = { $set: {} };
            setModifier.$set['stocks.'+index+'.price'] = req.body.price;
            Store.findOneAndUpdate ({"_id": tempId}, setModifier, function (err, documents){
                if(!err){
                    res.send({"status": 202, "message": "Price has updated"});
                }
                else{
                    res.send({"status": 400, "message" : "Error message" });
                }
            });
        }
    }
    else{
        res.send({"status": 400, "message" : "Error message" });
    }

  // console.log(data);
});

2 个答案:

答案 0 :(得分:0)

您缺少一对括号

更改

Store.update ({_id: storeId}, {'$set':"stocks.j.price":req.body.price});

Store.update ({"_id": storeId}, {'$set': { "stocks.j.price":req.body.price } });

答案 1 :(得分:0)

您的正确查询将是这样的

Store.update ({"_id": storeId,"stocks.price":45}, { $set:{ "stocks.$.price" : req.body.price}});

更多更新教程请访问以下链接

https://docs.mongodb.com/manual/reference/operator/update/positional/