skip to Main Content

I’m creating a MERN stack ecommerce application where I want send all user info along with jwt token but except password I’m ok with token part & I know how to send user but i don’t know how to exclude the password property while sending the user through res.json
enter image description here

3

Answers


  1. You can use the aggregation or select method in the mongoose.

    const users = await User.find({}, {name: 1, email: 1});
    or
    const users = await User.find({}).select("name email");
    or
    const users = await User.aggregate([{"$project": {name: 1, email: 1}}]);
    
    Login or Signup to reply.
  2. Modified Answer –
    @prathamesh

    You can change the default behavior at the schema definition level using the select attribute of the field:

    password: { type: String, select: false }

    Then you can pull it in as needed in find and populate calls via field selection as ‘+password’. For example:

    Users.findOne({_id: id}).select(‘+password’).exec(…);

    Login or Signup to reply.
  3. I use this way to save all attributes except password in another variable and then I show info.

    let {password, ...foundUser} = user.toJSON();
    response.setStatus(200).setRes(foundUser);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search