'TypeError: User.generateAuthToken is not a function
userSchema.methods.generateAuthToken = async function() {
const user = this
const token = jwt.sign({_id:user._id.toString()},'thisisnewcourse')
return token}
const token = await User.generateAuthToken()
When I call the generateAuthToken(), its showing type error. Line 1 is showing error.
Solution 1:[1]
I think there is naming error, Try this.
userSchema.methods.generateAuthToken = async function() {
//try using Camel notation here(User(U with uppercase))
const User = this
const token = jwt.sign({_id:user._id.toString()},'thisisnewcourse')
return token}
const token = await User.generateAuthToken()
Solution 2:[2]
I'm not sure if you are calling generateAuthToken() method at schema or not.
when calling generateAuthToken() method it refers to the instance of the user model getting from request, not to the User it self. so wehn you create a schema first assign the methods to it and then pass this schema to your model.
Example: User model
const userSchema = new mongoose.Schema({
// your scehma
});
// assign methods to schema
userSchema.methods.generateAuthToken = async function() {
const user = this
const token = await jwt.sign({_id:user._id.toString()},'thisisnewcourse')
return token
}
// now pass this schema to User model
const User = mongoose.model('User', userSchema);
now call the method based on your logic.
// when calling generateAuthToken() method
const token = await user.generateAuthToken();
// here 'user' is the instance of the 'User model' which holds the request body data.
// if it's post request for authentication
e.g. let user = await User.findOne({ name: req.body.name });
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nithin K Joy |
Solution 2 | Rushi Kadivar |