0

I am getting values returned from mongodb in docs in the below code

collection.find({"Stories._id":ObjectID(storyId)}, {"Stories.$":1}, function (e, docs) {

        var results = docs;
        results[0].Stories = [];
}

I am assigning the value of docs to results. Then i change one array in that results to an empty array. The problem i face is, if I change the value of results, the value of docs is also getting affected!! How can i change value of results[0] alone?

A simple JSFIDDLE link

Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150
  • [Related, maybe tenuous dupe](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) - `var results = docs;` isn't cloning the data. – James Thorpe Aug 10 '15 at 10:51

2 Answers2

0

This is because in java-script array and object are mutable by nature. If y is an object, the following statement will not create a copy of y:

var x = y;  // This will not create a copy of y.

The object x is not a copy of y. It is y. Both x and y points to the same object.

Any changes to y will also change x, because x and y are the same object.

You can use simply use of following solution:

In Jquery

    results = $.extend(true,{},docs);//For deep copy
    results = $.extend({},docs);//For shallow copy
    results = JSON.parse(JSON.stringify(docs))

In Javascript

function clone(obj) {
       var target = {};
       for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
         target[i] = obj[i];
        }
       }
       return target;
      }

results = clone(docs);
Juned Lanja
  • 1,466
  • 10
  • 21
0

You can change the value of 'results[0]' alone without effecting the 'docs' by using the scope concept. Try making the changes in a function rather than in an immediate line or at the same hierarchy. I have written a sample here at Fiddle A few months back, I was experimenting on how the concept of pass by reference works in terms of Objects in JS. We have to note that the return type of ds.find() is a json. You can read my article here Thanks.

var docs = [1,2,3];
var results = docs;
console.log(results[0]);


var documents =[ {
'stories':'eshwar',
'place':'Hyd'
},
            {
'stories':'Prasad',
'place':'Del'
},
            {
'stories':'Hari',
'place':'Chennai'
}]

console.log(documents[2]); //prints {stories: "Hari", place: "Chennai"}

function ChangeAlone(documents){
var refDoc = documents;
refDoc[2] =[];    
}
// the value of stories remains same in the parent object without change
console.log(documents[2].stories); //prints Hari