1

I have model(auth.model.js) like below

const User = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 3,
        maxlength: 50
    },
    email: {
        type: String,
        required: true,
        minlength: 3,
        maxlength: 255,
        unique: true
    },
    password: {
        type: String,
        required: true,
        minlength: 3,
        maxlength: 1024,
    },
})
   // this one I'm accessing outside of the file and it is not returning any value
    User.methods.generateAuthToken = function () {
        const token = jwt.sign({
            email: this.email
        }, 'jwtPrivateKey');
        return token;
    }
    // this one I'm accessing outside of the file and it is returning value
    User.static.generateAuthToken = function (a) {
        const token = jwt.sign({
            email: this.email
        }, 'jwtPrivateKey');
        return token;
    }

exports.User = mongoose.model('User', User);

to get the token in auth.controler.js I'm trying to accessing like below

const {
    User,generateAuthToken
} = require('../models/user.model');

and it has for the static method

const token = User.generateAuthToken(req.body.email);

for schema.methods

const token = User.generateAuthToken();

when I try to accessing the static method it is working fine, where as when I try to accessing the schema.method it is not returning any thing.

why it is not working schema.method. could any please let me know the reason or any thing wrong implementation in my code

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
change need
  • 137
  • 2
  • 6
  • 23
  • 1
    The difference of `method` vs `static` is that `User.generateAuthToken()` is the **static** method, much like a `static` on a class definition in various other languages or even ES6 classes. The **method** would be invoked from an **instance** of the "class". i.e `let user = new User(); let token = user.generateAuthToken();` As such the **method** has access to the **current instance data**. A **static** on the other hand **does not**. Therefore the the `this` in a `static` does not see `this.email` as an existing value. – Neil Lunn May 04 '19 at 03:02

0 Answers0