如何在 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 );
});
});
但是 结果
是空的,并且没有错误。我还希望能够按名称仅获取所需的集合,而不必过滤 collections
返回的内容(如果可能的话)。
I have a problem where I want to be able to get all the unique cities for a collection, and my code looks something like this:
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var PersonSchema = new Schema({
name: String,
born_in_city: String
});
var Person = mongoose.model('Person', PersonSchema);
In native MongoDb I could just do db.person.distinct("born_in_city")
, but there doesn't seem to be anything equivalent for Mongoose. Is the only option to iterate over all of the documents myself to do this, or is there a better solution?
In an attempt to use the underlying node-mongodb-native
as suggested by the answerer I attempted to do this:
mongoose.connection.db.collections(function(err, collections){
collections[0].distinct('born_in_city', function( err, results ){
console.log( err, results );
});
});
However the results
is empty and there's no error. I would also prefer to be able to fetch only the needed collection by name rather than have to filter what collections
return if at all possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只是提供 Mongoose 3.x 的更新:
Just to give an update for Mongoose 3.x:
在我的程序中,这段代码有效。
经过
节点.js v0.4.7,
猫鼬1.3.3
In my program, this code works.
by
node.js v0.4.7,
mongoose 1.3.3
我通读了源代码,node-mongodb-native 驱动程序为该类提供了动力。那么在连接对象上。因此,在完成 mongoose.connect(mongodb://) 之后,您可以尝试一下。
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.