I found a solution for myself, where I just create a little helper method on the Schema to remove whatever field it may be.
Example User Schema (simplified):
const UserSchema = new Schema(
{
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
},
password: {
type: String,
required: true,
trim: true
},
},
{
timestamps: true
}
);
const User = mongoose.model("User", UserSchema);
module.exports = User;
For a reasons of security, I like removing the password salt from a User object when sending back to client. I might make a helper method in my UserSchema
, like:
UserSchema.methods.hidePasswordSalt = function() {
let self = this;
self = self.toObject();
if (self.password) {
delete self.password;
}
return self;
};
Then, in my Controller, etc, when I retrieve my User
, I call the method and send the result:
User.findOne({ _id: req.session.userId })
.then(user => {
user = user.hidePasswordSalt(); // removes password field
return res.status(200).json(user);
})
.catch(error => {
return res.status(403).json(error.errors);
});