Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I delete a mongoose model's object properties?

When a user registers with my API they are returned a user object. Before returning the object I remove the hashed password and salt properties. I have to use

user.salt = undefined; user.pass = undefined; 

Because when I try

delete user.salt; delete user.pass; 

the object properties still exist and are returned.

Why is that?

like image 760
JuJoDi Avatar asked Apr 28 '14 13:04

JuJoDi


People also ask

How do we delete the object property?

Remove Property from an ObjectThe delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.

Which operator can be used to delete properties from object?

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

How will you delete the property of the object student?

You can use the delete operator with . or [ ] to remove the property from an object.


2 Answers

To use delete you would need to convert the model document into a plain JavaScript object by calling toObject so that you can freely manipulate it:

user = user.toObject(); delete user.salt; delete user.pass; 
like image 151
JohnnyHK Avatar answered Oct 02 '22 16:10

JohnnyHK


Non-configurable properties cannot be re-configured or deleted.

You should use strict mode so you get in-your-face errors instead of silent failures:

(function() {     "use strict";      var o = {};      Object.defineProperty(o, "key", {          value: "value",          configurable: false,          writable: true,          enumerable: true      });      delete o.key; })() // TypeError: Cannot delete property 'key' of #<Object> 
like image 30
Esailija Avatar answered Oct 02 '22 14:10

Esailija