It is not possible to prevent this scenario. The user
attribute is already set to the object doc[0]
. Subsequently, when you modify the .password
attribute of this newly assigned object, it will affect the original object as well. To segregate the password
, you must assign a different object to doc[0]
.
req.session.user = {};
req.session.user.doc = doc[0];
req.session.user.password = null;
Below is a function for duplicating/extending an object:
var duplicate = function() {
var process = function(target, source) {
for (var property in source) {
if (Object.prototype.hasOwnProperty.call(source, property)) {
target[property] = source[property];
}
}
return target;
};
var output = arguments[0];
for(var j=1; j<arguments.length; j++) {
output = process(output, arguments[j]);
}
return output;
};
An example of how to utilize the function:
var initial = { value: "hello" };
var copied = duplicate({}, initial, { newAttribute: "example"});