Search code examples
javascriptnode.jsmongoosemongoose-schema

Unable to Call Mongoose Static Method : Error findByCredential is not a Function


I have defined a PatientSchema, And a findByCredentials Static method onto that Schema as shown below :

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}

Now when I try to access it from my Login Controller, I get the Error : Patient.findByCredentials is not a function. Here is my Controller Code :

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

I am calling the Method from the Model and not the instance, still i am getting this error :(


Solution

  • You should declare the model after assigning the static method:

    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}