I am using mongoose with express and node to create a REST API. Upon saving a new object, I want to return the object to the user. However, do not want to return some sensitive fields, like password, credit card details, permissions, billing history, etc.
I thought that there would be the equivalent of .select where you can select just a subset of fields to return to the user. However, it looks like this does not exist, and the 'standard' is just to delete fields you do not want to pass back to the user, like so:
org.save(function(err, org) {
if (err) return handleError(err, res);
orgobj = org.toObject();
delete orgobj.__v;
delete orgobj._id;
delete orgobj.billing;
delete orgobj.plans;
delete orgobj.permissions;
return res.send(orgobj);
});
Is there a more efficient way? I don't like this, because if there is subsequently a field added, someone has to remember to specifically remove it. Also, I don't want to 're-select' the field either, for performance reasons.
You may add a method, getPublicFields
which returns an object containing strictly the public fields.
orgSchema.methods.getPublicFields = function () {
var returnObject = {
name: this.name,
address: this.address,
randomField: this.randomField
};
return returnObject;
};
You may also add a callback to that function and perform some other queries to aggregate data, if you wish to do that. After the method is complete, just call
var orgPublic = org.getPublicFields();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With