Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda