I have this following error thrown when calling a custom method.
user.model.js
const userSchema = new Schema({
(... HERE GOES THE SCHEMA ...)
}, {
timestamps: true
});
/**
* Login check password method
*/
userSchema.methods.checkPass = function (password, callback) {
bcrypt.compare(password, this.password, function (err, same) {
if (err) {
callback(err);
} else {
callback(err, same);
}
});
}
auth.js
router.route('/').post((req, res) => {
let findUser = User.findOne({
username: req.body.username
}, function (err, user) {
if (err) {
// err
} else if (!user) {
// err
} else {
findUser.checkPass(req.body.password, function (err, same) {
// THIS IS NOT CALLED!
// Error thrown: TypeError: findUser.checkPass is not a function
})
}
})
});
How it cannot be a method if checkPass is put as a method on the Schema?
Thank you for your time!
SOLVED!
I was using the User
schema when calling the method instead of calling user
from the callback of findOne
.
Solved code:
User.findOne({
username: req.body.username
}, function (err, user) {
if (err) {
// Error!
} else if (!user) {
// Error!
} else {
user.checkPass(req.body.password, function (err, same) {
if (err) {
// Error!
} else if (!same) {
// Invalid !
} else {
// SUCCESS !
}
})
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.