我有一段代码可以找到数字字段“ordinal”的最高值的记录:
Job.find({}).sort({'ordinal': -1}).limit(1).then(maxOrd => {
console.log(`Found MaxOrd: ${maxOrd}`);
});
这很好用。现在我想让它成为 Job
模式的静态方法。正如我尝试的那样:
JobSchema.statics.findMaxOrdinal = function(callback) {
Job.find({}, callback).sort({'ordinal': -1}).limit(1);
};
...和:
Job.findMaxOrdinal().then(maxOrd => {
console.log(`Found Max Ord using Promise: ${maxOrd}`);
});
但这是行不通的,并且崩溃时出现了一个非常无用的堆栈跟踪。
如何编写我的静态文件以便我可以将它与 Promise 一起使用?
最佳答案
像这样返回 Mongoose 查询:
JobSchema.statics.findMaxOrdinal = function() {
return Job.find({}).sort({'ordinal': -1}).limit(1);
};
关于javascript - 将 Promises 与 Mongoose 模型静态结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43895150/