While exploring mongoose for nodejs I ran into the problem of needing to know the amount of user in my collection:
My collection has records, each record has a user. I want to know the amount of unique (different) users.
How can I do this with mongoose?
EDIT:
The database is growing quite fast, is there anyway to get the number back from the DB instead of getting all the distinct records and counting them?
Here’s an alternative answer as I get an exception when I try Reddest’s approach with Mongoose 3.1.2 (which seems like a bug in Mongoose to me as Reddest’s approach should be fine).
You can call the
distinctmethod on your collection’s model, specifying the name of the user-identifying field of that collection:Or if you want to chain the
distinctcall from a find, include the callback in thedistinctcall (this did work for me):UPDATE
If you just want the count without getting the values, stick a
count()call in the chain:NOTE: this doesn’t work in the latest Mongoose code (3.5.2).