DEV Community

loading...

How to exclude password from mongoose mongodb

Akshat Singhania
I am a passionate full stack developer from India , I like making websites , apps and games (basically everything)
・1 min read

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

Discussion (0)