Mongoskin - 聚合查询抛出错误,在mongo cli中正常工作

时间:2014-11-16 06:13:29

标签: node.js mongodb express mongoskin

所以我有一个相当简单的mongo查询,我试图从集合中返回一个唯一年份列表。我有一个使用mongo CLI构建的聚合查询,它返回我正在寻找的结果:

db.rides.aggregate([{'$group': {_id: {year: {'$year': '$date'}}}},{'$sort' : {'_id.year' : -1}}])

当我将此插入使用mongoskin作为db驱动程序的Express应用程序时,会抛出错误

db.collection('rides').aggregate([{'$group': {_id: {year: {'$year': '$date'}}}},{'$sort' : {'_id.year' : -1}}]).toArray(function(err, years) {
    res.json(years);
});

错误:

TypeError: Cannot read property 'readPreference' of undefined
at Collection.aggregate (/Users/Shared/projects/fitness-tracker/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/collection/aggregation.js:260:17)
at EventEmitter.<anonymous> (/Users/Shared/projects/fitness-tracker/node_modules/mongoskin/lib/utils.js:120:34)
at EventEmitter.g (events.js:180:16)
at EventEmitter.emit (events.js:98:17)
at /Users/Shared/projects/fitness-tracker/node_modules/mongoskin/lib/utils.js:169:27
at Db.collection (/Users/Shared/projects/fitness-tracker/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/db.js:503:44)
at EventEmitter.<anonymous> (/Users/Shared/projects/fitness-tracker/node_modules/mongoskin/lib/collection.js:51:21)
at EventEmitter.g (events.js:180:16)
at EventEmitter.emit (events.js:98:17)
at /Users/Shared/projects/fitness-tracker/node_modules/mongoskin/lib/utils.js:169:27

我可以找到类似的报告,无法将聚合查询与mongoskin一起使用。不止一些人建议只使用本机mongo驱动程序,但我的堆栈跟踪与我见过的任何东西都不同。我的查询中有什么突出的问题吗?有什么想法吗?

由于

1 个答案:

答案 0 :(得分:4)

您的汇总查询syntax有误,它应该采用callback函数,如下所示:

db.collection('rides').aggregate([{'$group': {_id: {year: {'$year': '$date'}}}},
    {'$sort' : {'_id.year' : -1}}],function(err, years) {
    console.log(years);
});

并处理callback函数中的响应。你可以在那里得到你的结果阵列。