Mongoose模式引用和未定义types“ObjectID”

我试图在我的模式之间做一些关系,我的解决scheme有一些问题。 这是我的设备架构:

var deviceSchema = schema({ name : String, type : String, room: {type: mongoose.Types.ObjectId, ref: 'Room'}, users: [{type:mongoose.Types.ObjectId, ref: 'User'}] }); 

这里的房间模式:

 var roomSchema = schema({ name : String, image : String, devices: [{type: mongoose.Types.ObjectId, ref: 'Device'}] }); 

mongoose引发错误

TypeError:未定义的types在room ObjectID你尝试嵌套模式? 你只能使用参考或数组嵌套。

如果我改变room: {type: mongoose.Types.ObjectId, ref: 'Room'}, to room: {type: Number, ref: 'Room'},一切正常。 你能解释一下为什么会发生这种情况吗?

mongoose.Types.ObjectIdObjectId构造函数,您要在模式定义中使用的是mongoose.Schema.Types.ObjectId (或mongoose.Schema.ObjectId )。

所以deviceSchema应该看起来像这样:

 var deviceSchema = schema({ name : String, type : String, room: {type: mongoose.Schema.Types.ObjectId, ref: 'Room'}, users: [{type:mongoose.Schema.Types.ObjectId, ref: 'User'}] });