简体   繁体   English

ZCCADDEDB567ABAE643E15DCF0974E503Z:查找父级并更新嵌套的 object

[英]Mongoose: Find parent and update nested object

Problem问题

I have the following object:我有以下 object:

[
   {
      "_id":"1",
      "store":"llama.com",
      "items":[
         {
            "_id":"1_1",
            "name":"item1"
         },
         {
            "_id":"1_2",
            "name":"item2"
         }
      ]
   },
   {
      "_id":"2",
      "store":"frog.com",
      "items":[
         {
            "_id":"2_1",
            "name":"item1"
         },
         {
            "_id":"2_2",
            "name":"item2"
         }
      ]
   }
]

In this object, I need to:在这个 object 中,我需要:

  1. Find the store;找到商店;
  2. Find an item by _id通过_id查找item
  3. Update the item's name更新项目的名称

Solutions tried尝试的解决方案

I tried using aggregate but I'm only able to find the object, not modify it:我尝试使用aggregate ,但我只能找到 object,而不是修改它:

const ObjectId = mongoose.Types.ObjectId;
const item = await UserModel.aggregate([
  { $unwind: "$items" },
  {
    $match: { store, "items._id": ObjectId("1_1") },
  },
]);

Desired outcome期望的结果

How can I find an item by store , then find the item child by _id and finally change the name of the found item ?如何按store查找商品,然后按_id查找商品子项,最后更改找到的item的名称?

Thank you in advance!先感谢您!

In the store and items._id you put your variables that you want to search.storeitems._id中,您放置要搜索的变量。 $set changes the name here. $set在此处更改名称。

This works for 1 level nested array.这适用于 1 级嵌套数组。 For deeper nested arrays you should go with arrayFiltershttps://docs.mongodb.com/manual/release-notes/3.6/#arrayfilters For deeper nested arrays you should go with arrayFiltershttps://docs.mongodb.com/manual/release-notes/3.6/#arrayfilters

const item = await UserModel.findOneAndUpdate(
  {
    store: "some store",
    "items._id": "your id"
  },
  {
    $set: {
      [`items.$.` + variable]: "change your name"
    }
  }
);

See if this works看看这是否有效

   const item = await UserModel.findOneAndUpdate({ "store": "storeName", 
                "items._id" : "id" },{$set:{"items.0.name":"itemName"}}, {new: true})

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

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