0

Currently my User model looks like:

{
  _id: 'SomeId'
  firstName: 'John',
  lastName: 'Cena',
  books: [
  { 
   _id: 'xyz',
    title: 'a', 
    author:'b', 
    ratings:[
      {source:'source1', value:"8"},
      {source:'source2', value:"9"}] 
  },

  {
    _id: 'abc',
    title: 'c', 
    author:'d',
    ratings:[
      {source:'source3', value:"7"},
      {source:'source4', value:"5"}] 
   }
 ]
}

I want to update the rating=>value of 1st book(_id:'xyz') object from 8 to 10 for a given source(say "source1"). I expect the follwing output:

{
  book: [{ rating:[{source:'source1', value:"10"}] }    
}

Please help me to write findOneAndUpdate query correctly. Here is my attempt, it updates the rating value correctly but project both the books.rating.

 let up={
     'books.$[book].ratings.$[rating].value':10
       }
  let filter={
      new:true,
      'books.rating':1,         //I just want rating array of updated objects in it
     arrayFilters:[
        { 'book._id':'xyz'},   
        { 'rating.source': 'source1'}
        ]
    }
  User.findOneAndUpdate({'_id':'userId','books._id':'xyz'},up,filter).select('books.rating').exec((err,doc)=> {
  if (err) throw err;
  console.log(doc);
  }

Output of my code:

{
_id: 'SomeId'
books: [ { ratings: [Array] }, { ratings: [Array] } ] 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.