Add object to empty array

This the document

_id: "5f1d78511158a201f89eaa13" ,
name: "Course",
sections:  [
    {
    _id: "5f1d7d723bfe781024f734d9" ,
    section: "Section 1",
    lessons: [ Array ]
    }  
   {
    _id: "5f1d7fd5131e9020d0477b18" ,
    section: "Section 1",
    lessons: [ Array ]
    ]
}

I would like to push an object into the ‘lessons’ array that is completly empty, so I should use findByIdAndUpdate()
lesson: {
content: “Content”
}

I get the course and section id from the request, so I tried this but it doesn’t work

db.collection.findByIdAndUpdate( {'sections._id':  req.body.section }, {$push: {lessons: lesson}, updated: Date.now()}, {new: true})

I really need help, I haven’t found anything useful in the internet. What I should do?

Thank you very much,
Sule

Hello @Soulaimane_Benmessao, welcome to the forum.

You can use the positional $ Update Operator to update (i.e., add object to the empty array field lessons, using the update operator $push) the document for the specified "sections._id" field value.

For example, the following mongo shell update method will update the specific sub-document with a matching "sections._id":

db.collection.findOneAndUpdate( 
  { "sections._id": req.body.section }, 
  { 
      $push: { "sections.$.lessons": lesson }, 
      $set: { updated: Date.now() } 
  },
  { returnNewDocument: true }
)
2 Likes

It works perfectly fine. Now I understand it. Thank you very much!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.