Mongoose更新文档数组子文档

时间:2016-04-12 15:50:31

标签: node.js mongodb

我有这个包含subSchema数组的模式,如下所示:

var timesheetSchema = mongoose.model('Timesheet', new Schema({
  _owner: {
      type: Schema.Types.ObjectId,
      ref: 'User'
  },
  name: {
      type: String,
      required: true
  },
  members: [memberSchema],
  slots: [slotSchema]
}), 'Timesheet');

Slot schema(有点遗憾)

var slotSchema = mongoose.model('Slot', new Schema({
  _email: {
    required: true,
    type: String
  },
  description: {
    required: false,
    type: String
  },
  date: {
    required: true,
    type: Date
  },
  from: {
    required: true,
    type: Date
  },
  to: {
    required: true,
    type: Date
  }
}), 'Slot');

尝试将新插槽推入slots[],但这似乎不起作用!

var query = Timesheet.findByIdAndUpdate(
    { '_id': timesheetId },
    { '$push': { 'slots': newSlot }}
);

query.exec(function (error) {
    if (error) {
        console.log(error);
        return next(error);
    }

    return res.sendStatus(200);
});

错误

 [CastError: Cast to undefined failed for value "[object Object]" at path "slots"]
  message: 'Cast to undefined failed for value "[object Object]" at path "slots"',
  name: 'CastError',
  kind: undefined,

它说插槽未定义但时间表确实有slots[]enter image description here

有些检查

 console.log('Timesheet:' + timesheet);
 console.log('NewSlot:' + newSlot);        
 console.log('Timesheets slots: ' + timesheet.slots);

结果

Timesheet:{ 
  members: [],
  slots: [],
  __v: 0,
  name: '2211221',
  _owner: 570babdcbc431d20afeea445,
  _id: 570d14f90482bf5d15a895e2 }
NewSlot:{ 
  _id: 570d18beb3d3c57715b4ee75,
  to: Tue Apr 12 2016 16:36:09 GMT+0200 (CEST),
  from: Tue Apr 12 2016 16:36:09 GMT+0200 (CEST),
  date: Tue Apr 12 2016 16:36:09 GMT+0200 (CEST),
  description: 'WEINIG',
  _email: 'test1' }
Timesheets slots: undefined

如果需要更多信息,我会尽快更新我的问题!

提前致谢。

0 个答案:

没有答案