我正试图在我的模式之间做一些关系,我的解决方案有些问题.
这是我的设备架构:
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'}]
});
猫鼬抛出错误
TypeError: Undefined type
ObjectID
atroom
Did you try nesting
Schemas? You can only nest using refs or arrays.
如果我改变房间:{type:mongoose.Types.ObjectId,ref:’Room’},到房间:{type:Number,ref:’Room’},一切正常.你能解释一下为什么会这样吗?
解决方法:
mongoose.Types.ObjectId是ObjectId构造函数,您要在模式定义中使用的是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'}]
});