【发布时间】:2015-05-10 22:37:23
【问题描述】:
我正在为猫鼬模型编写一些测试,它包含一个引用另一个模型的字段。我运行 before() 并创建一个对象,然后运行我的测试。在创建的回调中,我看到该对象在正确的字段中有一个 ID。在第一个“it”语句中,我还看到了 ID 并且我的测试通过了。在随后的每个“it”语句中,它都会消失并且为空。我发现如果我事先实际创建了引用的对象,那么该字段仍然存在。我不认为 mongoose/mongo 实际上会检查所有 ObjectId 引用,但如果确实如此,有谁知道它是如何/为什么工作的?如果不是,究竟是什么原因导致了这种现象?
消失的字段是 OfficeHoursSchema 中的“主机”字段。顺便说一句,即使 required 设置为 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}
});
测试:
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;
});
});
第一个 it 语句通过,但第二个 .host 字段为 Null。
这基本上是有效的
工作:
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 是否存在于其他地方进行某种检查,但有人能指出我对这种行为的一些文档吗?非常感谢您阅读本文。
【问题讨论】:
-
你希望这会做什么
var hostId = new mongoose.Types.ObjectId;? -
我希望它会给我一个随机生成的 ID,其类型是猫鼬中特定的 ObjectId 类型。
标签: node.js mongodb mongoose mocha.js