0

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!

1 Answer 1

1

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'}...
Sign up to request clarification or add additional context in comments.

5 Comments

I'm facing one more issue with this problem...findOneAndUpdate updates that book correctly but gives me every book object as output although I have added 'book.$': 1 & new:trueas option...
You need to use fields option. But you cannot use a positional projection and return the new document so you need to use $elemMatch. Something like: {fields: {book: {$elemMatch: {_id: req.params.id}}}, new: true}
Positional projection are giving unexpected results now after executing this query more than one time....it's actually pushing same book object multiple times {'book.$.isbn': '15'}
What do you mean? Can you provide more details?
Brother... Help me for this question: stackoverflow.com/questions/58375310/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.