Mongoskin -- aggregate query throws error, works fine in mongo cli

1.9k views Asked by At

So I have a fairly simple mongo query where I'm attempting to return a list of unique years from a collection. I have an aggregate query that I've constructed using the mongo CLI and it returns the results that I'm looking for:

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

When I plug this into my express app which uses mongoskin as the db driver, it throws an error

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

Error:

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

I can find similar reports of trouble getting aggregate queries to work with mongoskin. More than a few have recommended just using the native mongo driver, but my stack trace is different than anything I've seen. Does anything in my query standout as being a problem? Any ideas?

Thanks

1

There are 1 answers

1
BatScream On BEST ANSWER

Your aggregation query syntax is wrong, it should take a callback function as below:

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

and handle the response in the callback function. There is where you will get your resultant array.