1

I have a node js function:

function func() {
  USER.find({},function(err, users){
    user = users[0];

    console.log(user); // {"name":"mike", "age":15, "job":"engineer"}
    user.name = "bob"; //{"name":"bob", "age":15, "job":"engineer"}
    delete user.name;
    console.log(user); // {"name":"mike", "age":15, "job":"engineer"} name still there??
  });
}

Here USER is a mongoose data model and find is to query the mongodb. The callback provide an array of user if not err. The user data model looks like

{"name":"mike", "age":15, "job":"engineer"}.

So the callback is invoked and passed in users, I get the first user and trying to delete the "name" from user. The wired part is I can access the value correctly and modify the value. But if I 'delete user.name', this element is not deleted from json object user. Why is that?

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
pythonician_plus_plus
  • 1,244
  • 3
  • 15
  • 38
  • do also `console.log(delete user.name)`, it should return `true`, otherwise, it couldn't be deleted for somehow – jperelli Aug 05 '15 at 05:37

2 Answers2

8

As others have said, this is due to mongoose not giving you a plain object, but something enriched with things like save and modifiedPaths.

If you don't plan to save the user object later, you can also ask for lean document (plain js object, no mongoose stuff):

User.findOne({})
.lean()
.exec(function(err, user) {

  delete user.name; // works
});

Alternatively, if you just want to fetch the user and pay it forward without some properties, you can also useselect, and maybe even combine it with lean:

User.findOne({})
.lean()
.select('email firstname')
.exec(function(err, user) {

  console.log(user.name); // undefined
});
Zlatko
  • 18,936
  • 14
  • 70
  • 123
4

Not the best workaround, but... have you tried setting to undefined?

user.name = undefined;
jperelli
  • 6,988
  • 5
  • 50
  • 85
  • Good suggestion, it worked. But why 'delete' doesn't work? – pythonician_plus_plus Aug 05 '15 at 05:36
  • 3
    @MattSun [http://stackoverflow.com/questions/23342558/why-cant-i-delete-a-mongoose-models-object-properties](http://stackoverflow.com/questions/23342558/why-cant-i-delete-a-mongoose-models-object-properties) may be helpful. – letiantian Aug 05 '15 at 05:38
  • maybe reading this helps http://perfectionkills.com/understanding-delete/ I was trying to find why, by reading that – jperelli Aug 05 '15 at 05:38