简体   繁体   中英

How to update a nested array field inside another nested array in mongo DB using Mongoose Node JS

There is a document that has a nested array inside a nested array. In one of the cases, I want to update the child array of child array.

    {
        "_id": "62da8472669b750870b094f6",
        "name": "Test Expert",
        "user_id": "62bdabee9aa50c0028d60767",
        "services": [
            {
                "service_name": "Hello 2",
                "service_id": "62ce7393534bda04d40f42c3",
                "_id": "62ce7394534bda04d40f42c4",
                "videos": [
                    {
                        "_id": "62da8472669b750870b094f8",
                        "lv_guid_id": "fsdfdshflsdhj",
                        "status": "REQUESTED" //Need to update this element status
                    },
 {
                        "_id": "62da8472669b750870b09sdw",
                        "lv_guid_id": "gdfgdfgfdg",
                        "status": "REQUESTED" //Need to update this element status
                    }
                ]
            }
        ],
        "__v": 0
    }

In this above document, I want to update the element inside videos array and this videos array are nested array of services array.

This is what I tried but I couldn't get the second nested array position.

 this.findOneAndUpdate(
    { _id: new mongoose.Types.ObjectId(orderID), "services._id": new mongoose.Types.ObjectId(videoDetail.service_id), "services.videos.lv_guid_id": videoDetail.lv_guid_id },
    {
      $set: {
        "services.$.videos./*Need to fetch the position of this element to update*/.status": videoDetail.status
      }
    },
    { upsert: true, new: true }
  );

You can use arrayFilters condition,

  • create a variable v and check the condition for lv_guid_id
this.findOneAndUpdate(
  { 
    _id: new mongoose.Types.ObjectId(orderID), 
    "services._id": new mongoose.Types.ObjectId(videoDetail.service_id)
  },
  {
    $set: { "services.$.videos.$[v].status": videoDetail.status }
  },
  {
    arrayFilters: [{ "v.lv_guid_id": videoDetail.lv_guid_id }],
    upsert: true,
    new: true
  }
)

Playground

Note: you can not upsert sub document/array element

All you have to do is "services.$.videos.$.status" if I get you right. Give it a try.

this.findOneAndUpdate(
    {  _id: new mongoose.Types.ObjectId(orderID), "services._id": new mongoose.Types.ObjectId(videoDetail.service_id), "services.videos.lv_guid_id": videoDetail.lv_guid_id },
    { $set: { "services.$.videos.$.status": videoDetail.status } },
    { new: true },
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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