0

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.

Alex Blex
  • 34,704
  • 7
  • 48
  • 75
lpares12
  • 3,504
  • 4
  • 24
  • 45
  • I don't think there is an option for create method. Out of curiosity why do you need it to be removed? – Alex Blex Jul 14 '22 at 10:22
  • I'm gonna return the object to the user, and don't want to show the hashed password to him. And setting it to `null` feels sloppy. And I really don't want to call `toJson` if I can avoid it. Looks like it is either converting to json or setting to `null`. – lpares12 Jul 15 '22 at 07:02
  • If the "user" is not within the same nodejs thread calling toJson is unavoidable, even if you do it implicitly. I'd recommend to shape the response before you send it out rather than on model level. You know separation of concerns etc. – Alex Blex Jul 15 '22 at 08:37

0 Answers0