Reputation: 7705
I have the following code in javascript in my node.js application.
However certain objects are not stored in my variable appointment
. Even if I set them, when I directly access them it works: console.log(appointment.test);
What have I done wrong in this code?
var appointment = {
subscribed: false,
enoughAssis: false,
studentSlotsOpen: false
};
console.log(appointment);
for (var key in appointmentsDB[i]) {
appointment[key] = appointmentsDB[i][key];
}
appointment.test= "res";
console.log(appointment.test);
console.log(appointment);
And here is the produced output:
{ subscribed: false,
enoughAssis: false,
studentSlotsOpen: false }
res
{ comment: 'fsadsf',
room: 'dqfa',
reqAssi: 3,
maxStud: 20,
timeSlot: 8,
week: 31,
year: 2013,
day: 3,
_id: 51f957e1200cb0803f000001,
students: [],
assis: [] }
The variable console.log(appointmentsDB[i])
looks as:
{ comment: 'fsadsf',
room: 'dqfa',
reqAssi: 3,
maxStud: 20,
timeSlot: 8,
week: 31,
year: 2013,
day: 3,
_id: 51f957e1200cb0803f000001,
students: [],
assis: [] }
The following command:
console.log(Object.getOwnPropertyNames(appointmentsDB[i]), Object.getOwnPropertyNames(Object.getPrototypeOf(appointmentsDB[i])));
Shows:
[ '_activePaths',
'_events',
'errors',
'_maxListeners',
'_selected',
'_saveError',
'_posts',
'save',
'_pres',
'_validationError',
'_strictMode',
'isNew',
'_doc',
'_shardval' ] [ 'assis',
'timeSlot',
'db',
'_schema',
'id',
'base',
'day',
'collection',
'reqAssi',
'constructor',
'comment',
'year',
'room',
'students',
'week',
'_id',
'maxStud' ]
However I would expect that my last output also provides the entries test, subscribed, enoughAssis and studentSlotsOpen. What is wrong in this code?
The solution I found was to manually copy the elements I wanted to.
Upvotes: 4
Views: 2867
Reputation: 664484
You probably have a Document object instead of a plain object. Those have a custom toJSON
method which only yields the properties of your schema and the _id
, but nothing else. If you are copying that method with your for-in-loop onto the appointment
object, it will get serialized differently as well when logged.
Try
for (var key in appointmentsDB[i].toObject()) {
appointment[key] = appointmentsDB[i][key];
}
appointment.test= "res";
console.log(appointment);
Upvotes: 5