3

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 actually in a mongo database.)

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"

etc

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 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?

Dave Sag
  • 13,266
  • 14
  • 86
  • 134

1 Answers1

6

For these kind of queries you can use use native method to execute raw MongoDB command:

Dog.native(function(err, collection) {
    collection.distinct('breed', function(err, dogs) {
        // do something here
    });
});
Dave Sag
  • 13,266
  • 14
  • 86
  • 134
Christian P
  • 12,032
  • 6
  • 60
  • 71