Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

Below is my code

var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); 

var Cat = mongoose.model('Cat', { 

name: String, 

age: {type: Number, default: 20},

create: {type: Date, default: Date.now} 

}); 

Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}},function(err, doc){ 

if(err){ 

console.log("Something wrong when updating data!"); 

console.log(doc); 

});

I already have some record in my mongo database and I would like to run this code to update the name for which age is 17 and then print the result out at the end of code.

However, why I still get the same result from the console(not the modified name) but when I go to mongo db command line and type "db.cats.find();". The result came with modified name.

Then I go back to run this code again and the result is modified.

My question is: If the data was modified, then why I still got original data at the first time when console.log it.

2 Answers

0 votes
by (106k points)

Anyone who is using the Node.js driver instead of Mongoose, you'll want to use {returnOriginal:false}instead of {new:true}.

0 votes
by (50.2k points)

The original, unaffected document is returned from default. If we want a new, latest or updated document to be returned you have to pass an additional argument: an object with the new property and set it to true.

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
0 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...