Javascript 无法调用Mongoose静态方法:错误findByCredential不是函数

Javascript 无法调用Mongoose静态方法:错误findByCredential不是函数,javascript,node.js,mongoose,mongoose-schema,Javascript,Node.js,Mongoose,Mongoose Schema,我在该模式上定义了PatientSchema和findByCredentials静态方法,如下所示: const Patient = mongoose.model('Patient', PatientSchema ) PatientSchema.statics.findByCredentials = async function(patientId,password) { const patient = await Patient.findOne({patientId}) i

我在该模式上定义了PatientSchema和findByCredentials静态方法,如下所示:

const Patient = mongoose.model('Patient', PatientSchema )
PatientSchema.statics.findByCredentials = async function(patientId,password) {

    const patient = await Patient.findOne({patientId})

    if(!patient) {
        throw new Error ('No Such Patient Exists')
    }

    if(password !== patient.password) {
        throw new Error ('Incorrect Password !')
    } else {
        return patient
    }

}


module.exports = {Patient}

现在,当我尝试从登录控制器访问它时,我得到一个错误:Patient.findByCredentials不是一个函数。这是我的控制器代码:

const {Patient} = require('../../models/Patient.model')


router.post('/', async (req,res)=>{

    if(req.body.userType === 'Patient') {
        const patient = await Patient.findByCredentials(req.body.id, req.body.password)
        const token = await patient.generateAuthToken()
        res.send({patient, token})
    } 
}) 

module.exports = router

我是从模型而不是从实例调用该方法,但我仍然收到以下错误:(

在分配静态方法后,您应该声明该模型:

PatientSchema.statics.findByCredentials = async function(patientId,password) {

    const patient = await Patient.findOne({patientId})

    if(!patient) {
        throw new Error ('No Such Patient Exists')
    }

    if(password !== patient.password) {
        throw new Error ('Incorrect Password !')
    } else {
        return patient
    }

}

const Patient = mongoose.model('Patient', PatientSchema )
module.exports = {Patient}

在没有模型的情况下,我如何访问findOne方法?我认为在模式中使用静态方法调用模型上的方法是不正确的做法。您需要使用
schema.methods
在这种情况下,我通过在静态方法定义后声明模型来修复它。实际上,这似乎是一种做法在模式静态方法中调用Model方法的方法不是很好,会导致很多混乱。不过,感谢您的帮助:)