Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After saving an object using mongoose, what is the simplest way I can return an object with a subset of fields?

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.

like image 753
Scott Switzer Avatar asked Dec 16 '22 15:12

Scott Switzer


1 Answers

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();
like image 57
randunel Avatar answered Dec 20 '22 16:12

randunel