How to access a specific value from mongoose request callback?

First, a small introduction to the situation. I have a MongoDB collection filled with documents. I use schema.statics to query a specific string

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 request is completed, it calls the callback (cb).

In the callback, I want to bind the values ​​to variables so that I can use them later. This is what I can not solve:

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

console.log(result.id_str) == 'undefined'

The same goes for:

console.log(result[0].id_str)

Why can't I get a specific value? Type (result) says “object”.

Update per request My loose schema made Mongoose return an unreal javascript object. Therefore, for further use here, the "scheme" I used:

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

I did not want to define everything, since it is a Twitter Timeline object and therefore not always the same.

+4
1

undefined, json find javascript. toObject(), , , , :

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     
})

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
})
+4

All Articles