How can I delete a property from object returned by mongoose

Viewed 1175

I am querying users collection and I don't want to send back password. My main point is that if I can perform javascript operations on mongodb objects or not. Here is my code:

router.get("/:userId", async (req, res) => {
  try {
    const user = await User.findById(req.params.userId);
    delete user.password;
    if (user.parent !== undefined) {
      const referrer = await User.findOne({ _id: user.parent });
      return res.json({ user, referrer });
    }
    res.json(user);
  } catch (error) {
    res.status(400).json(error);
  }
});

I am getting this output

{
    "is_deleted": false,
    "packages": [],
    "_id": "5ed102f3fefa080404db01df",
    "name": "parent",
    "email": "parent@parent.com",
    "gender": "m",
    "password": "$2b$10$HTGaoy.AVmoG/A0c/vkikO0NnEBte7f2tvwt2FQE94bZlNiYTeX8i",
    "__v": 0
}

I tried to perform filter on a list of mongodb objects and that failed too.

2 Answers

You can destructure the object returned from the query

const {password, ...restProps } = await User.findById(req.params.userId);
const user = restProps;

You can also configure your User model so that password field is excluded by default from query result.

const UserSchema = new mongoose.Schema({
    ...
    password: {
       ...
       select: false
    }
});

if you don't want to exclude a field by default, you can call select function and specify the properties you don't want to include in the query results.

const user = await User.findById(req.params.userId).select('-password');

for more info on this, see SchemaType.prototype.select()

I would use findeOne with the projection on the end:

const user = await User.findOne({ _id: req.params.userId },{ password: 0 });

You can exclude more fields with setting the value to 0

Related