json - Mongodb更新语句: How do i update the json object?

标签 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);
});

最佳答案

您的正确查询将是这样的

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

更多更新教程请访问下面的链接

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

关于json - Mongodb更新语句: How do i update the json object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45138125/

相关文章:

javascript - 如何从 MongoDB 文档获取值(value)

node.js - 如何将 Node.js 与 IPv6 结合使用?

javascript - 加载存储在 IPFS 上的 javascript 模块

ruby-on-rails - 如何实现has_many :through relationships with Mongoid and mongodb?

mongodb - React Native 上的 Realm Sync 离线优先 : how to implement?

Javascript 使用变量作为键从 json 中获取值

java - 使用 Jackson 进行序列化和反序列化 : how to programmatically ignore fields?

Json 路径 - 对列表列表进行过滤

node.js - 具有两个字段和条件的 mongoosastic 搜索

java - 如何将 jsonNode 转换为 BasicDbList