1

I am experimenting with node authentication, I have managed to store a username and a hashed password into my database, but I want to return the json back without the hashed password.

I am deleting the password key before sending the JSON back but the password still shows in the returned result.

router.post("/signup", async (req, res, next) => {
  const user = await User.exists({ username: req.body.username });

  if (user) {
    const error = new Error("Username already exists");
    next(error);
  } else {
    const newUser = new User({
      username: req.body.username,
      password: req.body.password,
    });

    try {
      const result = await newUser.save();
      delete result.password;
      res.json(result);
    } catch (err) {
      res.json(err.errors);
    }
  }
});

the User model has a pre hook to hash the password before save:

userSchema.pre("save", async function save(next) {
  const user = this;

  if (!user.isModified("password")) return next();

  try {
    user.password = await bcrypt.hash(user.password, 12);
    return next();
  } catch (err) {
    return next(err);
  }
});
Ollie2619
  • 1,255
  • 4
  • 17
  • 28

1 Answers1

7

Here is the solution thanks to Mahan for pointing it out. result returns a Mongoose object so needs turning into a normal Javascript object first.

try {
      let result = await newUser.save();
      result = result.toObject();
      delete result.password;
      res.json(result);
    } catch (err) {
      res.json(err.errors);
    }
Ollie2619
  • 1,255
  • 4
  • 17
  • 28