0

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.

  • A wild guess from me would be an issue with the `this` call, try giving the function a parameter and call the parameter.username etc. maybe that works – Branchverse Dec 07 '21 at 20:25
  • @MaximilianDolbaum Hello This has worked thanks. However why does `this` not work? – NodeNinja08 Dec 07 '21 at 20:28
  • See https://stackoverflow.com/a/3127440/2282634 – Joe Dec 08 '21 at 10:05
  • You are creating arrow function to generateAuthToken, which don't have any context. if you create function using 'function' keyword, issue will be resolved. – Shashikamal R C Dec 08 '21 at 11:29

0 Answers0