Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 794
Christopher Thonfeld-Guckes Avatar asked Oct 18 '25 10:10

Christopher Thonfeld-Guckes


1 Answers

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
});

or

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

respectively.

like image 94
devonj Avatar answered Oct 21 '25 01:10

devonj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!