Search code examples
mongooseinstance-methods

Instance Methods inside Mongoose Schema not working


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.


Solution

  • '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: {},
        },
      )