Subhendu Mahanta Subhendu Mahanta - 1 year ago 71
Node.js Question

Why the callback in mongoose code getting document as null?

I have following code:

var mongoose = require('mongoose');
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}});;
Character.findOne({name : 'Frodo'},function(error, 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


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 Source is a async call so it returns a Promise, and you search by Charachter.findOne immediately the line after which happens before the 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:
  .then(function() {
    Character.findOne({name : 'Frodo'}, function(error, character) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download