将承诺与猫鼬模型静态配合使用

Joh*_*ing 2 javascript mongoose

我有一段代码可以找到数值字段“ ordinal”中具有最高值的记录:

Job.find({}).sort({'ordinal': -1}).limit(1).then(maxOrd => {
    console.log(`Found MaxOrd: ${maxOrd}`);
});
Run Code Online (Sandbox Code Playgroud)

这很好。现在,我想使它成为Job架构的静态方法。因此,我尝试:

JobSchema.statics.findMaxOrdinal = function(callback) {
    Job.find({}, callback).sort({'ordinal': -1}).limit(1);

};
Run Code Online (Sandbox Code Playgroud)

...和:

Job.findMaxOrdinal().then(maxOrd => {
    console.log(`Found Max Ord using Promise: ${maxOrd}`);
});
Run Code Online (Sandbox Code Playgroud)

但这不起作用,并且由于非常无用的堆栈跟踪而崩溃。

我该如何编写我的static,以便可以在Promise中使用它?

小智 5

只需返回猫鼬查询,像这样:

JobSchema.statics.findMaxOrdinal = function() {
    return Job.find({}).sort({'ordinal': -1}).limit(1);
};
Run Code Online (Sandbox Code Playgroud)