Home > Net >  Push values in Mongo Nested Array
Push values in Mongo Nested Array

Time:10-14

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!

CodePudding user response:

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

Here we tried to find document with filtering it's own id and barbers id. You can change the filter as you wished. It can be only search on barbers id.

Need to write your DocumentName and your parameters instead of idValue, barbersId, 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 providedServices array into this barbers array.

  • Related