Using Waterline from Sails 0.10 is there a way to find distinct values from my database collection?

2,131 views
Skip to first unread message

Dave Sag

unread,
Jun 21, 2014, 6:07:50 AM6/21/14
to sai...@googlegroups.com
Using `Sails.js` version `0.10.x`, assume I have a model `Dog`, populated as follows (writtenout in `yaml` format for convenience, but in my case it's in a `mongo` db.)

    dogs:
    -  breed: "wolf"
       name: "Fido"
    -  breed: "wolf"
       name: "Roger"
    -  breed: "dingo"
       name: "Nipper"
    -  breed: "dingo"
       name: "Ernie"
    -  breed: "corgi"
       name: "Bernadi"
    -  breed: "corgi"
       name: "Queenie"
    -  breed: "poodle"
       name: "Christopher"
    -  breed: "poodle"
       name: "Tony"

So now I want to create a list of the available breeds.

    Dog.find().exec(err, dogs) {
      breeds = [];
      dogs.each(function(dog)) {
        if (breeds.indexOf(dog.breed) === -1) breeds.push(dog.breed);
      }
      ...
    }
    
Is there a simpler way to do this with fewer hits on the database? Something like

    Dog.find().distinct('breed').exec(function(err, breeds){
      ...
    });

I've found [this closed Waterline issue](https://github.com/balderdashy/waterline/issues/60) which seems to indicate that I could use a `.distinct` method but I tried it and alas no dice.

    Object [object Object] has no method 'distinct'
    
How might I go about this in a database efficient manner?


Cheers

Dave

Dave Sag

unread,
Jun 21, 2014, 10:25:44 AM6/21/14
to sai...@googlegroups.com
Just to let you know, someone on Stackoverflow worked this out for me - the answer was to use Dog.native…

cheers

dave

Ambroise Dhenain

unread,
Jun 21, 2014, 11:02:28 AM6/21/14
to Dave Sag, sai...@googlegroups.com
A link would be great ;)

Dave Sag

unread,
Jun 21, 2014, 11:10:30 AM6/21/14
to Ambroise Dhenain, sai...@googlegroups.com

Mandeep Gulati

unread,
Jun 23, 2014, 7:44:42 AM6/23/14
to sai...@googlegroups.com
It's already resolved but just for the record, whenever you need some functionality which you are not able to find in waterline, look for the same in the database's native code. for SQL databases, waterline provides Model.query() function to execute the SQL queries. And for mongodb, it provides Model.native() function for the same. 

Since Mongodb has an api helper function distinct, you can use this in Model.native(). 
Reply all
Reply to author
Forward
0 new messages