How to access specific value from mongoose query callback?

12,025

When you are using an undefined schema, the json output from find can't be handled like a real javascript object. Use toObject() to convert it and you will be able to use it as you would any other object, you can see the difference here:

var Model = mongoose.model('Model', new mongoose.Schema({}))
Model.find({user_id: '1234'}, function(err, obj) {   
    console.log(obj[0].user_id)  // undefined                   
    console.log(obj[0].toObject().user_id)  // 1234     
})

or:

var Model = mongoose.model('Model', new mongoose.Schema({
    user_id: String,
}))
Model.find({user_id: '1234'}, function(err, obj) {                      
    console.log(obj[0].user_id)  // 1234          
    console.log(obj[0].toObject().user_id)  // 1234
})
Share:
12,025
Roland
Author by

Roland

Updated on June 13, 2022

Comments

  • Roland
    Roland almost 2 years

    First a little introduction to the situation. I have a MongoDB collection filled with documents. I use a schema.statics to query a particular row

    TweetSchema.statics.maxAndLimit = function(screen_name, cb) {
      this.find({
        'user.screen_name': screen_name
      }).sort({'id_str':1}).select({'id_str':1,'user.statuses_count':1,'user.screen_name':1,'_id':0}).limit(1).exec(cb);
    };
    

    When the query is finished it calls the callback (cb).

    In the callback I want to bind the values to variables so I can use them later. This is what I can't seem to solve:

    console.log(result) == [{id_str:'12346875',user:{statuses_count:500,screen_name:'username'}}]
    
    console.log(result.id_str) == 'undefined'
    

    Same goes for:

    console.log(result[0].id_str)
    

    Why can I not get a specific value? The typeof(result) says 'object'.

    Update per request My non-strict schema caused Mongoose to return a non-real javascript object. So for future reference here's the 'schema' I used:

    var TweetSchema = new Schema({}, {strict: false});
    

    I didn't want to define everything as it's a Twitter Timeline object and thus not always the same.

  • Raeesaa
    Raeesaa almost 10 years
    Any idea how to update document of such type? I am using non-strict mongoose schema and I am trying to update an array in record as author.toObject().books.push(someObject) and then author.save() but document is not getting updated.
  • Mattias Farnemyhr
    Mattias Farnemyhr almost 10 years
    toObject is just a json dict. its not a model so you can't change it.
  • Raeesaa
    Raeesaa almost 10 years
    hmmm. How can one modify documents of non-strict mongoose schemas then?
  • Mohamed Sohail
    Mohamed Sohail over 7 years
    Fantastic! Solved my problem!