DEV Community

Akshat Singhania
Akshat Singhania

Posted on

How to exclude password from mongoose mongodb

While logging or registering the user , we generally return the user data , password or hashed password is also returned along with the data , we do not want to send the hashed password to frontend so how do we exclude.

exclude password from returned object


After creating user

const createdUser = await User.create({
  email: email,
  password: await argon2.hash(password),
if (createdUser) {
  const { password, ...responseUser } = createdUser._doc;
  return { user: responseUser };
Enter fullscreen mode Exit fullscreen mode

the ._doc contains the data like email , username , password which we specify in the schema


let user = await User.findOne({ email: email });
if (user) {
  if (await argon2.verify(user.password, password)) {
    const { password, ...responseUser } = user._doc;
    return { user: responseUser };
  } else {
    return {
      error: [{ field: "password", message: "wrong password" }],
Enter fullscreen mode Exit fullscreen mode

We do the same thing but after finding the user

Thanks for reading, hearts ❤️ if you liked it and unicorns 🦄 if you loved it, follow if you wanna read more awesome blogs

Top comments (1)

agboola_iyanu profile image

This was helpful