How to extract distinct values from a mongo database using Waterline and Sails.js (version 0.10)?

╄→гoц情女王★ 提交于 2019-12-12 09:58:42

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/24340490/how-to-extract-distinct-values-from-a-mongo-database-using-waterline-and-sails-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!