【发布时间】:2014-01-10 12:25:26
【问题描述】:
先简单介绍一下情况。我有一个充满文档的 MongoDB 集合。我使用 schema.statics 来查询特定的行
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);
};
当查询完成时,它会调用回调 (cb)。
在回调中,我想将值绑定到变量,以便以后可以使用它们。这是我似乎无法解决的问题:
console.log(result) == [{id_str:'12346875',user:{statuses_count:500,screen_name:'username'}}]
console.log(result.id_str) == 'undefined'
同样适用:
console.log(result[0].id_str)
为什么我不能得到一个特定的值? typeof(result) 表示“对象”。
根据请求更新 我的非严格模式导致 Mongoose 返回一个非真实的 javascript 对象。因此,为了将来参考,这里是我使用的“模式”:
var TweetSchema = new Schema({}, {strict: false});
我不想定义所有内容,因为它是 Twitter 时间线对象,因此并不总是相同。
【问题讨论】:
-
console.log(result[0])输出什么? -
{id_str:'12346875',user:{statuses_count:500,screen_name:'username'}}。所以没有 []。
-
是的,这就是我的预期,但是,如果这是真的,
console.log(result[0].id_str)肯定会输出'12346875'。你能尝试登录result[0].user -
我就是这么想的。 result[0].user == 'undefined' 也是如此。 Mongoose 或 nodeJS 中是否有任何可能影响回调对象的黑魔法?
-
并非如此,find 的回调将始终如下所示
function(err, result)其中 result 是与查询匹配的对象数组。err是undefinded我猜?
标签: javascript mongodb object mongoose