I am using mongoose's toJSON support as below:
userSchema.set('toJSON', { getters: true, virtuals: true, minimize: false })
now in the returned result from a mongoose object's toJSON() method call, I want to remove certain sensitive fields. How to do that?
In different way to explain the issue:
Some certain fields like 'password', 'token' which we would need only in query, but not in returned result, how to hide them from returning from all kind of queries?
Update: This finally what I ended up with and working like a charm:
userSchema.options.toJSON = {
getters: true,
virtuals: true,
minimize: false,
transform: function (doc, ret, options) {
delete ret.password
delete ret.authToken
return ret
}
}
you can customize how toJSON works on your schema like this:
/**
* adjust toJSON transformation
*/
mySchema.options.toJSON = {
transform: function(doc, ret, options) {
ret.id = ret._id;
delete ret.password;
delete ret.token;
delete ret._id;
delete ret.__v;
return ret;
}
};
doc
is the document to be serialized, ret
is the plain JS object that will be transformed into JSON. You may then manipulate ret
however you want.
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