Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×