0

I want display the data of a user after its been created, returning the user inside a async function using the following code:

const newUser = await user.save() return newUser

But I don't want it to be possible for the password to be seen.

I've already encountered this topic which contains a similar issue, and the best approach presented there is by placing select: false inside the password field of the schema definition. It works for find functions, but it doesn't for the document.save() callback.

Currently I'm achieving what I want by using a spread operation and resetting the password field:

const newUser = await user.save() return { ...newUser.toObject(), password: null }

Is there a better approach to achieve this?

ardmont
  • 105
  • 8

1 Answers1

0

use lodash, it is better library with clean code

return _.omit(newUser, ['password']);

or second thing you can use post save on schema level

schema.post('save', function(doc) {
  delete doc.password;
});
Muhammad Ali
  • 1,992
  • 1
  • 13
  • 20