Within my applicaton, I have the following schema:
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
minlength: 4,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 3,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 6,
maxlength: 1024
},
})
I also have the following model:
const User = mongoose.model("User", userSchema);
And finally I have a schema method:
userSchema.methods.generateAuthToken = () => {
const token = jwt.sign({_id: this._id, username: this.username, email: this.email},'KEYTEST');
console.log(this.username)
return token;
}
I then run the following code in one of my API routes:
user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
})
await user.save();
const token = user.generateAuthToken();
res.send(token)
I then call this API route in my frontend, and on the server console, I expect the value of this.username
to be printed to the console. Instead I get undefined. I get the same for this._id
and this.email
. Also, the user object is successfully created in mongodb and has the expected values for properties such as _id, username and email.
Does anyone know why I am getting undefined printed? Thanks.