mongoose – this.find()不存在

在我的模型中,我试图做一个静态的getUserByToken方法。 但是,如果我像文档中那样做的话,我就可以了

this.find is not a function 

我的代码如下所示:

 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const schema = new Schema({ mail: { type: String, required: true, validate: { validator: (mail) => { return /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[az][az])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i.test(mail); } } }, birthDate: { type: Date, required: true, max: Date.now, min: new Date('1896-06-30') }, password: { type: String, required: true }, ... }); schema.statics.getUserByToken = (token, cb) => { return this.find({ examplefield: token }, cb); }; module.exports.Schema = schema; 

我猜这只是一个简单的错误,但是,我不能编译模型,而是将静态函数添加到模式/模型中,因为这是通过启动时的init函数完成的,该函数编译所有模型。

任何人都可以帮助我呢?

你需要为你的静态函数使用一个正常的函数声明,而不是使用胖箭头语法,以便在函数中保留Mongoose的含义:

 schema.statics.getUserByToken = function(token, cb) { return this.find({ examplefield: token }, cb); };