我正在使用MongoDB,MongooseJS和Nodejs。
我有一个具有以下字段的Collection(称为Member)-
Country_id,Member_id,名称,分数
我想编写一个查询,该查询返回具有最高分数的会员,其中国家/地区ID = 10
我在MongooseJS中找不到适合的文档。
我在StackOVerflow上找到了这(这是MongoDB代码)
Model.findOne({ field1 : 1 }).sort(last_mod, 1).run( function(err, doc) {
var max = doc.last_mod;
});
但是,如何将其翻译成MongooseJS呢?
Member
.findOne({ country_id: 10 })
.sort('-score') // give me the max
.exec(function (err, member) {
// your callback code
});
检查猫鼬文档以进行查询,它们非常好。
如果您不想再次编写相同的代码,也可以向您的Member模型添加一个静态方法,如下所示:
memberSchema.statics.findMax = function (callback) {
this.findOne({ country_id: 10 }) // 'this' now refers to the Member class
.sort('-score')
.exec(callback);
}
稍后再致电 Member.findMax(callback)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句