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?
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.
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.
You can use the delete operator with . or [ ] to remove the property from an object.
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;
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With