I am trying to remove the password field in a UserModel after a create
call.
So basically I have User
defined as:
const UserSchema = new mongoose.Schema({
password: {
type: String,
required: true,
select: false,
},
});
const User = mongoose.model('User', UserSchema);
And the password is hashed in the pre
middleware, but don't want to return the hash either.
My user creation method is the following:
module.exports.save = async function(userData){
return await User.create(userData);
}
The select clause in the schema does not work when using User.create(userData)
. And the exclude did not work either.
I have tried adding a post
middleware and calling delete user.password
like so:
UserSchema.post('save', function(doc){
delete doc['password'];
//delete doc.password;
}
But also with no luck. What I did now as a work around is in the post
middleware, to set the password to null
.
I have seen this post: How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections? but all the responses here are for a find query and not a create.