gpt4 book ai didi

node.js - MongooseJS - 如何找到具有最大值的元素?

转载 作者:IT老高 更新时间:2023-10-28 13:07:20 26 4
gpt4 key购买 nike

我正在使用 MongoDB、MongooseJS 和 Nodejs。

我有一个包含以下字段的集合(称为成员) -

Country_id、Member_id、姓名、分数

我想编写一个查询,它返回具有最高分数的成员,其中 Country 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

});

检查 the mongoose docs for querying ,它们都很好。

如果您不想再次编写相同的代码,您还可以向您的成员模型添加一个静态方法,如下所示:

memberSchema.statics.findMax = function (callback) {

this.findOne({ country_id: 10 }) // 'this' now refers to the Member class
.sort('-score')
.exec(callback);
}

稍后通过 Member.findMax(callback)

调用它

关于node.js - MongooseJS - 如何找到具有最大值的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19751420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com