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,195
  • 4
  • 14
  • 27
  • I think the issue is because you define `const` instead of `let` for your result variable . – Mahan Jul 15 '20 at 14:41
  • I tried that but it didnt work :( – Ollie2619 Jul 15 '20 at 14:43
  • Like that, it should works normally. If you `console.log(result)` before the `res.json(result)`, can you see that the password has been deleted? If it's the case, maybe an other route is interfering with you response body (just a guess). – Jeiraon Jul 15 '20 at 15:21
  • If appears in the object before and after the delete – Ollie2619 Jul 15 '20 at 16:45
  • I think it is because the mongoose return object. – Mahan Jul 15 '20 at 17:17
  • 2
    Here is a solution for you: https://stackoverflow.com/questions/23342558/why-cant-i-delete-a-mongoose-models-object-properties – Mahan Jul 15 '20 at 17:17

1 Answers1

4

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,195
  • 4
  • 14
  • 27