我在node.js应用程序中的javascript中有以下代码。
但是,某些对象不存储在我的变量appointment
中。即使我设置了它们,当我直接访问它们时,它也可以工作:console.log(appointment.test);
我在这段代码中做错了什么?
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);
这是产生的输出:
{ 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: [] }
变量console.log(appointmentsDB[i])
看起来像:
{ comment: 'fsadsf',
room: 'dqfa',
reqAssi: 3,
maxStud: 20,
timeSlot: 8,
week: 31,
year: 2013,
day: 3,
_id: 51f957e1200cb0803f000001,
students: [],
assis: [] }
以下命令:
console.log(Object.getOwnPropertyNames(appointmentsDB[i]), Object.getOwnPropertyNames(Object.getPrototypeOf(appointmentsDB[i])));
节目:
[ '_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' ]
但是我希望我的上一次输出还提供条目test,subscribed,enoughAssis和studentSlotsOpen。这段代码有什么问题?
我找到的解决方案是手动复制我想要的元素。
答案 0 :(得分:3)
您可能有Document object而不是普通对象。那些有自定义toJSON
method只会产生您的架构和_id
的属性,但没有别的。如果您使用for-in-loop将该方法复制到appointment
对象上,则在记录时它将以不同方式进行序列化。
尝试
for (var key in appointmentsDB[i].toObject()) {
appointment[key] = appointmentsDB[i][key];
}
appointment.test= "res";
console.log(appointment);