Christopher Guckes Christopher Guckes - 2 months ago 13x
Node.js Question

Can mongoose get me all different values for a certain field?

I have a mongo database that stores the rooms in a hotel. There are different types of rooms (singles, doubles, etc.). I want the user to be able to define his own room type. Is it possible to get a list entries from mongoose that contains exactly one of each room type, similar to an SQL DISTINCT query?

I would rather avoid storing different room types in a separate model, since this would add additional complexity.

I'm using ES6, so if that simplifies it, go ahead.


I believe Mongoose also has its own version of distinct with a model object or distinct with a query object

For your example, seems like you could do either, so you can do either:

Model.distinct('room_type', function(err, room_types) {
    //do something with room_types


Model.find({}).distinct('room_type', function(err, room_types) {
    //do something with room_types