Mocha MongoDB Mongoose ObjectId ref在第一个'it'语句后消失

我正在为mongoose模型写一些testing,它包含一个引用另一个模型的字段。 我运行一个before()并创build一个对象,然后运行我的testing。 在创build的callback中,我看到对象在适当的字段中有一个ID。 在第一个“it”声明中,我也看到了ID和我的testing通行证。 在每一个“it”声明中,它都消失了,并且是空的。 我发现,如果我实际上事先创build引用的对象然后该字段仍然存在。 我不认为mongoose/ mongo实际上检查所有的ObjectId引用,但如果它确实,有没有人知道如何/为什么它的作品? 如果没有,究竟是什么原因造成了这种现象呢?

消失的字段是OfficeHoursSchema中的“主机”字段。 顺便说一句,即使所需的设置为false,这仍然不起作用。

模型定义:

var appointmentSchema = new Schema({ attendee: { type: Schema.Types.ObjectId, ref: "Student", required: false }, startTime: { type: Date }, duration: Number }); var statusStates = ['open','closed'] var OfficeHoursSchema = new Schema({ host: { type: Schema.Types.ObjectId, ref: "Employee" , required: true}, appointments: [appointmentSchema], description: String, location: String, startDateTime: { type: Date, default: Date.now }, endDateTime: { type: Date, default: Date.now }, status: { type: String, default: 'open' , enum: statusStates}, seqBooking: {type: Boolean, default: true} }); 

testing:

 describe('OfficeHours Model', function(){ var hostId = new mongoose.Types.ObjectId; var mins = 15; var numAppointments = ohDurationInMs/appointmentDuration; var officeHour; var officeHourToCreate = { host: hostId, appointments: appointmentsToCreate(), description: 'meeting', location: 'room 1', startDateTime: new Date(startTime), //3/6/2015 at 3:30pm EST endDateTime: new Date(endTime), //2 hours later. 3/6/2015 at 5:30pm EST totalDuration: ohDurationInMs/(60*1000) }; before(function(done){ OfficeHour.create(officeHourToCreate,function(err,createdOH){ officeHour = createdOH;; done(); }); }); it('1st It statement',function(){ expect(officeHour.host).to.be.ok; }); it('2nd It statement',function(){ expect(officeHour.host).to.be.ok; }); }); 

第一条语句通过,但第二条.host字段是空的。

这基本上是有效的

加工:

 before(function(done){ var employee = new Employee({password: 'asdfasdfsafasdf'}); employee.save(function(err,createdEmployee){ officeHourToCreate.host = createdEmployee._id; OfficeHour.create(officeHourToCreate,function(err,createdOH){ officeHour = createdOH;; done(); }); }) }); 

我觉得像某种检查ObjectId存在其他地方必须发生,但任何人都可以指向我的一些文件的这种行为? 非常感谢您阅读本文。

我想这是因为before()被调用的第二次,你引用实例化的ObjectId的事实,第二次是没有创build一个new如你所期望的。

你可以试试这个:

 before(function(done){ OfficeHour.create({ host: new mongoose.Types.ObjectId, // btw I've never seen that syntax for making a new random ID, but if it does what you want it to do then go ahead! appointments: appointmentsToCreate(), description: 'meeting', location: 'room 1', startDateTime: new Date(startTime), //3/6/2015 at 3:30pm EST endDateTime: new Date(endTime), //2 hours later. 3/6/2015 at 5:30pm EST totalDuration: ohDurationInMs/(60*1000) }, function(err,createdOH){ officeHour = createdOH;; done(); }); });