Mongoose - this.find()不存在

SWA*_*AGN 6 static-methods mongoose mongodb node.js

在我的模型中,我试图做一个静态的getUserByToken方法.但是,如果我在文档中这样做,我会得到

this.find is not a function
Run Code Online (Sandbox Code Playgroud)

我的代码看起来像这样:

'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|[a-z][a-z])|([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;
Run Code Online (Sandbox Code Playgroud)

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

任何人都可以帮助我吗?

Joh*_*yHK 6

您需要为静态函数使用常规函数声明,而不是使用fat-arrow语法,以便this在函数内保留Mongoose的含义:

schema.statics.getUserByToken = function(token, cb) {
    return this.find({ examplefield: token }, cb);
};
Run Code Online (Sandbox Code Playgroud)