Search code examples
mongodbmongoosemongodb-querymongoose-schema

Issue in updating fields in an array of embedded documents Mongoose?


Currently my User model looks like:

{
  _id: 'SomeId'
  firstName: 'John',
  lastName: 'Cena',
  book: [{_id:'xyz',title: 'a', author:'b', isbn:'10' },{_id:'abc',title: 'c', author:'d', isbn:'12' }]
}

After making an findOneAndUpdate query to update isbn field of book object whose _id matches with req.params.id:

router.post('/update_book/:id', (req, res) => { 
  User.findOneAndUpdate({'book._id':req.params.id},{book: {isbn: '15'} }, {new: true,'book.$': 
  1}).select('book').exec((err,doc)=>{
  console.log(doc);
  }
});

After above code my collection looks like:

{
  _id: 'SomeId'
  firstName: 'John',
  lastName: 'Cena',
  book: [{isbn:'15' }]
} 

It actually delete all other book objects and also removes other fields of matching book object. Please help me to write findOneAndUpdate query correctly!


Solution

  • You need to use the positional $ operator to update only the element that matches the query.

    Example:

    User.findOneAndUpdate({'book._id':req.params.id}, {'book.$.isbn': '15'}...