How can I get distinct documents on a field with Mongoose?
Problem
My code is:
Checkin.distinct field, conditions, (err, checkinResults) ->
doStuff()
However, checkinResults
is simply a series of ObjectId
's. I need the full document. Any ideas?
Problem courtesy of: Shamoon
Solution
The distinct
method only returns the selected field, not the whole documents, so you need two (or more) queries:
getCheckinsByX = (field, cb) ->
Checkin.find({ field }).limit(x).exec (err, checkins) ->
cb err, { field, checkins }
Checkin.distinct field, conditions, (err, results) ->
async.map results, getCheckinsByX, (err, checkinsByField) ->
# use list of checkins
This could generate a lot of db queries, so you might want to look into the aggregation framework, or a way of making a single Checkin
query + grouping on the client.
Solution courtesy of: Ricardo Tomasi
Discussion
View additional discussion.