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


jignesh kumar

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);'/submit', (req, res) => {
let update={
'books.$.title' : req.body.title,
'books.$.author' :
User.findOneAndUpdate({_id:req.body.user_id},{$push: update},{new: true}).exec(function(err, doc) {
if (err){

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 isn't required 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!

Continue reading...