node.js - Mongodb, nodejs: find an object and update its value
问题描述
I am struggling to find a solution to update client's data to the database. I have a document looking like this:
{
"_id": {
"$oid": "60249fccf992b73b340c7c94"
},
"username": "john",
"inv": {
"id01": {
"n": "Apple",
"r": "0"
},
"id02": {
"n": "Pear",
"r": "0"
},
"id03": {
"n": "Pear",
"r": "0"
},
"id04": {
"n": "GreenApple",
"r": "0"
}
}
}
and this is the json data sent from the client
{
"id02": {
"n": "Pear",
"r": "1",
"z": "-1.0001",
"x": "-2.34",
"y": "-2.41"
},
"id03": {
"n": "Pear",
"r": "1",
"z": "-1.0002",
"x": "-0.52",
"y": "-2.41"
}
}
I want to look for the objects from the json data sent by client in the database (for instance: "id02") and update its value. I am pretty new to Mongodb so I am struggling with finding the proper technique to do so.
The document should be looking like this
{
"_id": {
"$oid": "60249fccf992b73b340c7c94"
},
"username": "john",
"inv": {
"id01": {
"n": "Apple",
"r": "0"
},
"id02": {
"n": "Pear",
"r": "1",
"z": "-1.0001",
"x": "-2.34",
"y": "-2.41"
},
"id03": {
"n": "Pear",
"r": "1",
"z": "-1.0002",
"x": "-0.52",
"y": "-2.41"
},
"id04": {
"n": "GreenApple",
"r": "0"
}
}
}
I try this but it replaces everything in the "inv" with the new data
var addToSet = {};
for(var key in data)
{
addToSet[key] = data[key];
}
db.get().collection('userdata').updateOne({ username: ws.userId},{'$set': {'inv':addToSet}})
解决方案
- 我用这个: const Product = require(Path Model Moongose);
常量数据 = {
NameProducts: req.body.title,
TitleProducts: req.body.body,
PriceProducts: req.body.price,
TagesProducts: req.body.tags
};
await Product.updateOne({ _id: Find with your idea }, { $set: data });
推荐阅读
- python - 有没有添加许多列的简单方法?
- vb.net - 我将如何使用 ListBox 制作 If Then 语句?
- python-3.x - Flask/Keras webservice ModuleNotFoundError: No module named 'tensorflow_core.keras'
- c# - 在.net core API C#中解构具有1个属性的[FromBody]对象
- java - JavaFx Jar 文件不能在 linux 上运行(在 windows 上运行良好)
- typescript - 打字稿动态字符串联合
- xcode - Xcode 11.2.1 - 命令 CodeSign 失败,退出代码为非零
- tensorflow - 推理时张量流中的批量标准化
- c# - 使用相同的浏览器使用 System.Diagnostics.Process.Start 启动新网页
- mongodb - 如何将对象数组作为值分配给 Apache NiFi 中的属性