Search code examples
mongodbmongoosemongodb-querymongoose-schema

How can I update multiple fields in an array of embedded documents Mongoose?


My Mongoose model:

const userSchema = Schema({
  firstName: String,
  lastName: String,
  books: [{title: String, author: String, isbn: Number}]
});

I'd like to add a new title & author with a book object for each POST request. My current approach giving me positional operator did not find the match error :

var User = mongoose.model("User", userSchema);
router.post('/submit', (req, res) => {    
    let update={
              'books.$.title' : req.body.title,
              'books.$.author' : req.body.author
               }
    User.findOneAndUpdate({_id:req.body.user_id},{$push: update},{new: true}).exec(function(err, doc) {
      if (err){
        console.log(err);
        return;
      }
     res.send(doc);
    });
});

I expect the following result for two form submit(POST) with different author and title in my DB:

{
  _id: 'SomeId'
  firstName: 'John',
  lastName: 'Cena',
  books: [{title: 'a', author:'b' }, {{title: 'c', author:'d' }}]
}

I don't care about ISBN in both post as it's not required field in our schema. Since my books sub-document is empty at beginning so I'm not able not set positional operator ($) properly in my code. Please help me to write findOneAndUpdate query correctly!


Solution

  • $push requires field name and value, in your case field name is book and value is an object {author, title}

    User.findOneAndUpdate({_id:req.user._id}, {$push : { books : { author: "c", title: "d"}}})