Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding a mongoose model method

I have the following express route:

app.post('/users/me',(req, res) => {
  var body =  req.body.email;
  User.find({
    email: body
  }).then((user) => {
    res.send({user});
  }, (e) => {
    res.status(400).send(e);
  });
});

On my User model I have the following method which limits results returned to email and _id:

UserSchema.methods.toJSON = function () {
    var user = this;
    var userObject = user.toObject();

    return _.pick(userObject, ['_id', 'email']);
};

In most of my routes that is exactly what I want however in this particular route I would like to return additional fields. How can I override\bypass the model method and have my fields returned?

like image 318
dwax Avatar asked Feb 19 '26 18:02

dwax


1 Answers

I found that I can create an additional method and call it in the res.send(). For example if I wanted to add Password as part of the return I can create a new Method:

UserSchema.methods.toPrivateJSON = function () {
    var user = this;
    var userObject = user.toObject();
    return _.pick(userObject, ['_id', 'email', 'activeAccount', 'password']);

};

Then in my route when I return the user object I call

res.send(user.toPrivateJSON());

This will invoke the toPrivateJSON() method and return the additional fields needed.

like image 100
dwax Avatar answered Feb 21 '26 08:02

dwax