0

I know this has been asked see this but the answer in directly modifying the database, but in this case I want to remove the password from user object so that password is not send to front-end, but delete is not working although user is an object.

User.find({}).then(function(users) {
    let counter = 1;
    users.forEach(function(user) {
        delete user.password;
        console.log("after delete",user) // password key/value exist

        userMap[counter] = user;
        counter++;
    });

    return userMap;
});

any idea !! i'm using mongoose

Saugat
  • 1,309
  • 14
  • 22
ashwintastic
  • 2,262
  • 3
  • 22
  • 49
  • 1
    It should have worked. Are you sure user has a field named exactly as "password". Can you show your console.log output as well? – Parijat Purohit Nov 04 '17 at 09:46

2 Answers2

1

You're trying to use the delete keyword on the Mongoose wrapper object. delete keyword will work with the native Javascript objects. For that you need to use the lean() function provided by Mongoose.

Try this -

User.find({}).lean().then

I just added the lean() function after the find query. Now your objects can be modified using the delete keyword.

Jyotman Singh
  • 10,792
  • 8
  • 39
  • 55
0

Why don't you exclude the password from the query itself? The second parameter of find let's you include/exclude the keys from your result.

User.find({}, { "password": 0 }).then(function(users) {
  // The users should not contain the password key here
});

I think this is available from Mongoose v4.0.0. Similarly, you can also use the select operator after find.

User.find({}).select({ "name": 1 }).then(function(users) {
  // Do something 
});

This query will only select the name of the users.

Saugat
  • 1,309
  • 14
  • 22