Instance Methods inside Mongoose Schema not working

29 views Asked by At

I'm trying to add 'methods' to a Schema. I assigned a function to the "methods" object through schema options. But it's not working (returns an error).

const userSchema = new mongoose.Schema({}, 

  { statics: {}}, 
  { methods: {   
      generateAuthToken() {
      const token = jwt.sign({ _id: this._id.toString() }, "nodejstraining");
      return token;
     },
  }
)

When I assign a function to the "methods" object, the code is working (I get the token):

userSchema.methods.generateAuthToken = function () {
    const token = jwt.sign({ _id: this._id.toString() }, "nodejstraining");
    return token;
};

This is a router:

router.post("/users/login", async (req, res) => {

try {
    const user = await ....  // I'm getting a 'user' here
    const token = await user.generateAuthToken();   
    
    res.send({ user, token });
  } catch (err) {
    res.status(400).send("Unable to login");
  }
});

Why the first option is not working? Thanks.

1

There are 1 answers

0
an_bozh On BEST ANSWER

'statics' and 'methods' should be parts of one argument.

Not

const userSchema = new mongoose.Schema({}, 
    { statics: {}},
    { methods: {}},
  )

But

const userSchema = new mongoose.Schema({}, 
    { 
        statics: {},
        methods: {},
    },
  )