Search code examples
mongodbmongoosemongoose-schema

Push values in Mongo Nested Array


enter image description here

Let's say that we have many documents like this in the photo

I have the above schema. I want to find the document based on _id first and then push an array of values to providedServices which belongs to the _id which is inside barbers array

A little help. Can't seem to find this out!


Solution

  • You need to find the related arrays first. For this, you can use $elemMatch or write it as 'barbers._id': { $elemMatch: parameter }.

    Here we tried to find the document by filtering its id and barbers id. You can change the filter as you wish. It can be only filtered on barbers id.

    $ Positional Operator can be used to update value.
    Also, see the MongoDB Documentation: Update Arrays in a Document

    Need to write your DocumentName and your parameters instead of idValue, barbersId, and serviceModel.

    const result = await DocumentName.findOneAndUpdate(
      {
       $and: 
         [
           { _id: mongoose.Types.ObjectId(idValue) }, 
           { barbers: { $elemMatch: { _id: mongoose.Types.ObjectId(barbersId) }}}
         ]
      },  
      { $push: { 'barbers.$.providedServices': serviceModel } },
      { new: true });
    

    At first, we found the related barbers array inside of all documents. Then we pushed the model inside of the providedServices array into this barbers array.