After saving an object using mongoose, what is the simplest way I can return an object with a subset of fields?
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 anyone is still interested in a more mongoose friendly answer see the following.
When you use .select(...)
you can see that the mongoose doc still has all its fields and the _doc
property is the one to be reduce.
What you can do is after saving a new doc remove the fields you want out of newDoc['_doc']
.
Now you are able to use the newDoc.toObject()
to pull the "public" fields you specified.
In the example below I'm using _.pick()
to create a white list the fields I want, but you can use _.remove()
to create a black list as well.
Note that the publicFileds
array can be use in the .select(...)
for querying so you only need one publicFileds
definition for your CRUD actions.
var MyModel = require('./MyModel');var _ = require('lodash');var publicFileds = ['_id', 'name', 'age'];function create(newModelData, cb) { var newModle = new MyModel(newModelData); newModle.save(function (err, newDoc) { if (err) { cb(err); return; } newDoc['_doc'] = _.pick(newDoc['_doc'], publicFileds); cb(null, newDoc); }}