pythonician_plus_plus
pythonician_plus_plus

Reputation: 1294

Cannot delete json element

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?

Upvotes: 1

Views: 3203

Answers (2)

Zlatko
Zlatko

Reputation: 19588

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
});

Upvotes: 8

jperelli
jperelli

Reputation: 7207

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

user.name = undefined;

Upvotes: 4

Related Questions