Subhendu Mahanta Subhendu Mahanta - 20 days ago 5
Node.js Question

Why the callback in mongoose code getting document as null?

I have following code:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test')
var Schema = mongoose.Schema;
var schema = new Schema({name : String, inventory: {}});
var Character = mongoose.model('Character',schema);
var Frodo = new Character({name: 'Frodo',inventory:{ringOfPower: 1}});
Frodo.save();
Character.findOne({name : 'Frodo'},function(error, character){
console.log(character);
});


I am running it as node optionminimize.js and null is getting logged to the console.It got persisted in mongodb alright, I opened a mongodb shell and ran

db.characters.findOne({name:'Frodo'})


and get following result:

{
"_id" : ObjectId("582fc3bab386f00ed0e7fede"),
"name" : "Frodo",
"inventory" : {
"ringOfPower" : 1
},
"__v" : 0
}


Why the document parameter in the callback is receiving null?

Answer

Frodo.save() is a async call so it returns a Promise, and you search by Charachter.findOne immediately the line after which happens before the Frodo.save() promise is resolved.

So, the search must be executed after the character is saved successfully, otherwise it returns null as you mentioned, so your code need to be like this:

Frodo.save()
  .then(function() {
    Character.findOne({name : 'Frodo'}, function(error, character) {
        console.log(character);
    });
  })