How to exclude some fields from the document How to exclude some fields from the document mongoose mongoose

How to exclude some fields from the document


Another way to handle this on the schema level is to override toJSON for the model.

UserSchema.methods.toJSON = function() {  var obj = this.toObject()  delete obj.passwordHash  return obj}

I came across this question looking for a way to exclude password hash from the json i served to the client, and select: false broke my verifyPassword function because it didn't retrieve the value from the database at all.


The documented way is

UserSchema.set('toJSON', {    transform: function(doc, ret, options) {        delete ret.password;        return ret;    }});

UPDATE - You might want to use a white list:

UserSchema.set('toJSON', {    transform: function(doc, ret, options) {        var retJson = {            email: ret.email,            registered: ret.registered,            modified: ret.modified        };        return retJson;    }});


Come across your question when I was trying to find a similar answer with pymongo. It turns out that in mongo shell, with the find() function call, you can pass a second parameter which specifies how the result document looks like. When you pass a dictionary with attribute's value being 0, you are excluding this field in all the document that come out of this query.

In your case, for example, the query will be like:

db.user.find({an_attr: a_value}, {_creator: 0});

It will exclude _creator parameter for you.

In pymongo, the find() function is pretty much the same. Not sure how it translate to mongoose though. I think it's a better solution compare to manually delete the fields afterwards.

Hope it helps.