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

Time:07-25

There is a document that has nested array inside nested array. In one of the case 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 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 }
  );

CodePudding user response:

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

CodePudding user response:

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 },
)
  • Related