Shamoon
Shamoon

Reputation: 43491

How can I get distinct documents on a field with Mongoose?

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?

Upvotes: 0

Views: 1698

Answers (1)

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35253

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.

Upvotes: 1

Related Questions