title: Mongoose Schema: TypeError: Cannot set property 'generateAuthToken' of undefined
body: <p>I am trying to create a method to userSchema however I get this error:</p>
  
  <blockquote>
    <p>TypeError: Cannot set property 'generateAuthToken' of undefined</p>
  </blockquote>
  
  <pre><code>userSchema.methods.generateAuthToken = function() {
    // const token = jwt.sign({ _id: user._id }, config.get("JWTPRIVATEKEY"));
    const token = jwt.sign({ _id: this._id }, "Privatekey");
    return token;
  };
  </code></pre>
  
  <p><strong>Note: I am not using arrow function instead its a normal function:</strong></p>
  
  <pre><code>var userSchema = {
    name: {
      type: String,
      require: true
    },
    email: {
      type: String,
      require: true,
      unique: true
    },
    password: {
      type: String
    }
  };
  
  userSchema.methods.generateAuthToken = function() {
    // const token = jwt.sign({ _id: user._id }, config.get("JWTPRIVATEKEY"));
    const token = jwt.sign({ _id: this._id }, "Privatekey");
    return token;
  };
  
  const User = mongoose.model("Users", new mongoose.Schema(userSchema));
  
  function validateUser(user) {
    let schema = {
      name: Joi.string().required(),
      email: Joi.string()
        .required()
        .email(),
      password: Joi.string().required()
    };
  
    return Joi.validate(user, schema);
  }
  
  exports.User = User;
  exports.validateUser = validateUser;
  </code></pre>
  
  <p><strong>Use case</strong></p>
  
  <pre><code>  let user = await User.findOne({ email: req.body.email });
  
    const token = user.generateAuthToken();
  </code></pre>