我的对象是这样的:
[
{
"_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/