如何使用Waterline和Sails.js(版本0.10)从mongo数据库中提取不同的值? [英] How to extract distinct values from a mongo database using Waterline and Sails.js (version 0.10)?
问题描述
使用Sails.js
版本0.10.x
,假设我有一个模型Dog
,填充如下(为方便起见,以yaml
格式写出,但在我的情况下,它实际上是在mongo
数据库中.)>
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){
...
});
我发现了这个封闭的水线问题,这似乎表明我可以使用.distinct
方法,但我尝试过,可惜没有骰子.
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?
推荐答案
对于这类查询,您可以使用native
方法执行原始的MongoDB命令:
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
});
});
这篇关于如何使用Waterline和Sails.js(版本0.10)从mongo数据库中提取不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!