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?
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.
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']);
};