如何在 Mongoose 中查询不同的值?

我有一个问题,我希望能够得到一个集合的所有唯一城市,我的代码看起来像这样:

var mongoose = require("mongoose"),
Schema = mongoose.Schema;


var PersonSchema = new Schema({
name: String,
born_in_city: String
});
var Person = mongoose.model('Person', PersonSchema);

在本地 MongoDb 中,我可以只执行 db.person.distinct("born_in_city"),但似乎没有任何与 Mongoose 相当的操作。是我自己迭代所有文档来完成这项工作的唯一选择,还是有更好的解决方案?

为了按照答案中的建议使用基础 node-mongodb-native,我试图这样做:

mongoose.connection.db.collections(function(err, collections){
collections[0].distinct('born_in_city', function( err, results ){
console.log( err, results );
});
});

但是 results是空的,没有错误。如果可能的话,我还希望能够仅通过名称获取所需的集合,而不是必须过滤 collections返回的内容。

117775 次浏览

I read through the source code and the node-mongodb-native driver is what powers the class. So on the connection object. So after you have done mongoose.connect(mongodb://), you can give this a shot.

if(mongoose.connections.length > 0) {
var nativeconn = mongoose.connections[0].conn;
nativeconn.person.distinct('born_in_city', function(error, results){


});
}

In my program, this code works.

Person.collection.distinct("born_in_city", function(error, results){
console.log(results);
});

by node.js v0.4.7, mongoose 1.3.3

Just to give an update for Mongoose 3.x:

MyModel.find().distinct('_id', function(error, ids) {
// ids is an array of all ObjectIds
});
const findBornCity = async() => {
const bornCity = await Person.find().distinct("born_in_city")
return bornCity
}