Syed Syed - 1 year ago 82
Node.js Question

mongoose document filtering properties

I have defined a schema like

var UserSchema = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true },
location: { type: String, required: true },
picture: { type: String, required: true },
passwordHash: { type: String, required: true },
resetPasswordToken: String,
resetPasswordExpired: Boolean

I have a REST Endpoint which return list of all users. In that list I want to hide some properties i.e,
passwordHash, resetPasswordToken, resetPasswordExpired

I defined a custom filter function like below

var doFilterUser = function(user) {
_.omit(user, ['passwordHash', 'resetPasswordToken', 'resetPasswordExpired']); = user._id;
delete user._id;
delete user.__v;
return user;

is lodash

When I check my API is responding with all user properties

This filter function is defined in common helper module and I am calling it like

User.findOne({_id: id}, function(err, user) {
var filtered = helper.doFilterUser(user);

How to resolve this issue?

Answer Source

The problem here is that you still have a mongoose document that conforms to s strict schema. If you want to change that document, then you need to make it a "raw" object without all the additional controls:

User.findOne({_id: id}, function(err, user) {
  var filtered = helper.doFilterUser(user.toObject());

So the .toObject() method here will return an object in it's raw form. That allows you to manipulate the keys how you wish.