Simple JS Question


#1

Hello,

it might be a noob question :-), but I don’t understand why I get my Plate object with changed values before I change it. Have anyone an idea? See my code snippet below:

var currentPlate = Plate.findOne({_id: currentPlateId}); //Object with {b1: false, b2: false, b3: false, b4: false, ...}
delete currentPlate._id;
console.log(currentPlate); //Why I get here the object with {b1: true, b2: true, b3: true, b4: true, ...}

for (var i = 1; i < 5; i++) {
    var name = 'b' + i;
    currentPlate[name] = true;
}

#2

Seems like the console shows what the object looks like at the moment, and not what the object looked like when it was logged.


#3

Your code snippet is not complete. The code you posted works as expected. See

Something else is causing the mutation.


#4

No my code snippet is complete. Before writing my issue here, I tried your example as well and it works like in your example. But if I get the Object from Mongodb it don’t work. Look on the attached screenshot:

Are the Mongodb methods synchronous or asynchronous. Could it be the reason because the mongodb methods are asynchronous? I don’t know where to turn.


#5

I tried now your example, look what happens, in one line it shows as false and if I select the object all items are true:


#6

That’s expected behavior. Javascript stores all non-primitive variables by reference. currentPlate references the same thing. When the console object is opened, it loads the current currentPlate which is now all true.


#7

Aha, ok I understand, thank you. I future I will be aware with log of objects. Thank you.