console.log不显示预期的对象属性

4
我在我的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这些条目。这段代码有什么问题吗?

我找到的解决方法是手动复制我想要的元素。


1
appointmentsDB[i] 是什么? - Bergi
它是从数据库检索出来的对象。 - tune2fs
你复制了自定义的 toStringtoJSON 方法吗? - Bergi
我使用的所有代码都在上面。 - tune2fs
当我在node.js中运行您的代码时,它可以正常工作(输出最后一个控制台日志的所有预期属性)。某个地方可能会干扰appointment。(我将i赋值为0,并将您指定的对象分配给appointmentsDB[0]。) - Ted Hopp
显示剩余3条评论
1个回答

5
你可能拥有一个文档对象而不是普通对象。这些对象具有自定义toJSON方法,该方法仅产生模式属性和_id,但没有其他任何内容。如果您将该方法与for-in循环一起复制到appointment对象上,则在记录日志时它也将以不同的方式进行序列化。
请尝试:
for (var key in appointmentsDB[i].toObject()) {
    appointment[key] = appointmentsDB[i][key];    
}

appointment.test= "res";

console.log(appointment);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接