DEV Community

Akshat Singhania
Akshat Singhania

Posted on

7 2

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

Register

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

Login

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (1)

Collapse
 
agboola_iyanu profile image
Qliqsee

This was helpful

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay