我已经定义了PatientSchema,并在该Schema上定义了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
我从模型而不是实例中调用方法,仍然出现此错误:(
答案 0 :(得分:1)
您应该在分配静态方法后声明模型:
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}