Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose findOneAndUpdate Updating Multiple Fields

Tags:

The findOneAndUpdate method doesn't work properly. I'm trying to update all the fields all at once but it's only updating (setting) the last field. It's always only the last field. Can someone tell me what I'm doing wrong or what can I do to have the expected effect?

This is my findOneAndUpdate code:

Book.findOneAndUpdate({_id:bookId},{$set:{"name": name},$set:{"genre": genre},$set:{"author": author},$set:{"similar": similar}}).exec(function(err, book){        if(err){            console.log(err);            res.status(500).send(err);        } else {             res.status(200).send(book);        } }); 
like image 290
pdace Avatar asked May 17 '16 04:05

pdace


People also ask

What is the difference between updateOne and findOneAndUpdate?

findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).

What does findOneAndUpdate return mongoose?

By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.

Is findOneAndUpdate Atomic?

According to these docs , single write transactions are atomic. So with findOneAndUpdate, this would indeed be atomic.


1 Answers

You are using the $set operator multiple times. The correct syntax for $set is :

{ $set: { <field1>: <value1>, ... } } 

You need to change your update argument like this:

Book.findOneAndUpdate({ "_id": bookId }, { "$set": { "name": name, "genre": genre, "author": author, "similar": similar}}).exec(function(err, book){    if(err) {        console.log(err);        res.status(500).send(err);    } else {             res.status(200).send(book);    } }); 
like image 131
styvane Avatar answered Oct 02 '22 10:10

styvane