简体   繁体   English

MongoDB通过动态ID更新嵌套项目

[英]MongoDB update nested item by dynamical ID

Hey i'm trying to update a nested Object in my MongoDB. 嘿,我正在尝试更新MongoDB中的嵌套对象。

They structure is 他们的结构是

[
 {
  "_id": "5871010d1ff9831574e7178d",
  "created_at": "2017-01-07T14:54:05.791Z",
  "updated_at": "2017-01-07T14:54:05.791Z",
  "place_id": "ChIJ1eTO6eS1vkcRL_mX2RWUKo4",
  "name": "Kunstwerk Restaurant Gummersbach",
  "__v": 0,
  "cooks": [],
  "menus": [
   {
    "58727068ba8d6c04a0ea331f": [
      {
        "intolerances": {
           "intolerance" : "false"
            ...
          },
        "nutritiondata" : [
          {...}
         ],
         "cookname": "testkoch@test.de",
         "menuname": "MenünameX"
      }
    ]
  }
]

The nested ID in menus is another ID of a MongoDB document which is created dynamicly. 菜单中的嵌套ID是动态创建的MongoDB文档的另一个ID。

I try to update the menuname, but cant access it, since mongo always returns null or doesnt find the element since in need to search for only the key not the key - value pair. 我尝试更新菜单名称,但无法访问它,因为mongo始终返回null或找不到元素,因为仅需要搜索键而不是键-值对。

What i tested so far: 我到目前为止测试的是:

db.restaurants.update({ 'menus.58727068ba8d6c04a0ea331f', { $set : {"menus.$.menuname" : "test"}}});

db.restaurants.findOne({ 'menus.58727068ba8d6c04a0ea331f' : "58727068ba8d6c04a0ea331f"});

db.restaurants.find({ menus : { $elemMatch : {"58727068ba8d6c04a0ea331f": "58727068ba8d6c04a0ea331f" }}});

db.restaurants.findOne({ menus : { $eq : "58727068ba8d6c04a0ea331f" }});

Use $set method as shown below : 使用$set方法,如下所示:

db.restaurants.update({"_id":"5871010d1ff9831574e7178d"}, {$set: {"menus.58727068ba8d6c04a0ea331f.0.menuname":"test"});

This will work only if you know the index of the item in the array that is being updated. 仅当您知道要更新的数组中项目的索引时,此方法才有效。 Check this Page , it has some good examples on updating multi level nested arrays, hope it will help. 检查此页面 ,它有一些更新多层嵌套数组的好例子,希望对您有所帮助。

So thanks to suzo i figgured out the solution. 因此,感谢suzo,我找到了解决方案。 The MongoShell code that works: 有效的MongoShell代码:

db.restaurants.update({"_id" : ObjectId("5871010d1ff9831574e7178d")}, {$set: {"menus.58727068ba8d6c04a0ea331f.0.menuname" : "testName"}});

UPDATE: Since my field is Mixed type, this isn't updating without getting marked!. 更新:由于我的字段是混合类型,因此没有被标记就不会更新! So here is the complete correct code: 因此,这是完整的正确代码:

 Restaurant.findOne({ _id : req.body.r_id }, function(error, restaurant){
    if(error) console.log(error);

    for(var i = 0; i < restaurant.menus.length; i++){
          restaurant.markModified('menus');
        if(restaurant.menus[i][req.params.id] != undefined){
            restaurant.menus[i][req.params.id].menuname = req.body.name;
        }

        if(i == restaurant.menus.length-1){
            restaurant.save();
            res.json(jObj);
        }
    }

  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM