[英]Using Promises with Mongoose Model Statics
I have a piece of code which finds the record with the highest value for a Numeric field, 'ordinal': 我有一段代码,它找到一个数字字段值最高的记录'ordinal':
Job.find({}).sort({'ordinal': -1}).limit(1).then(maxOrd => {
console.log(`Found MaxOrd: ${maxOrd}`);
});
This works fine. 这很好用。 Now I'd like to make this a static method of the
Job
schema. 现在我想使它成为
Job
模式的静态方法。 As so I tried: 所以我试过:
JobSchema.statics.findMaxOrdinal = function(callback) {
Job.find({}, callback).sort({'ordinal': -1}).limit(1);
};
...and: ...和:
Job.findMaxOrdinal().then(maxOrd => {
console.log(`Found Max Ord using Promise: ${maxOrd}`);
});
But this isn't working, and crashes with a very unhelpful stack trace. 但这不起作用,并且崩溃的堆栈跟踪非常无用。
How do I write my static so that I can use it with a Promise? 如何编写静态以便可以将其与Promise一起使用?
Just return mongoose query like this: 只需返回像这样的mongoose查询:
JobSchema.statics.findMaxOrdinal = function() {
return Job.find({}).sort({'ordinal': -1}).limit(1);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.