Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access specific value from mongoose query callback?

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.

like image 789
Roland Avatar asked Dec 21 '13 21:12

Roland


1 Answers

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
})
like image 115
Mattias Farnemyhr Avatar answered Oct 26 '22 01:10

Mattias Farnemyhr