Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

app.post('/users/me',(req, res) => {
  var body =  req.body.email;
  User.find({
    email: body
  }).then((user) => {
    user.private = true; //tells to model method to include additional fields
    res.send({user});
  }, (e) => {
    res.status(400).send(e);
  });
});

Then in the model method:

UserSchema.methods.toJSON = function () {
    var user = this;
    var userObject = user.toObject();
    if(user.private)
      return _.pick(userObject, ['_id', 'email', 'additionalField']);
    else
      return _.pick(userObject, ['_id', 'email']);
};
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!