Mongoose 模式引用和未定义的类型“ObjectID" [英] Mongoose schema reference and undefined type 'ObjectID'
问题描述
我正在尝试在我的模式之间建立一些关系,但我的解决方案有一些问题.这是我的设备架构:
I'm trying to do some relations between my schemas and I have some problems with my solution. Here is my device schema:
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
at room
您是否尝试过嵌套模式?您只能使用引用或数组进行嵌套.
TypeError: Undefined type
ObjectID
atroom
Did you try nesting Schemas? You can only nest using refs or arrays.
如果我将 room: {type: mongoose.Types.ObjectId, ref: 'Room'},
更改为 room: {type: Number, ref: 'Room'},
一切正常.你能解释一下为什么会这样吗?
If I change room: {type: mongoose.Types.ObjectId, ref: 'Room'},
to room: {type: Number, ref: 'Room'},
everything works. Could you explain me why this is happening?
推荐答案
mongoose.Types.ObjectId
是 ObjectId
构造函数,你想在模式定义中使用什么是 mongoose.Schema.Types.ObjectId
(或 mongoose.Schema.ObjectId
).
mongoose.Types.ObjectId
is the ObjectId
constructor function, what you want to use in schema definitions is mongoose.Schema.Types.ObjectId
(or mongoose.Schema.ObjectId
).
所以 deviceSchema
应该看起来像这样:
So deviceSchema
should look like this instead:
var deviceSchema = schema({
name : String,
type : String,
room: {type: mongoose.Schema.Types.ObjectId, ref: 'Room'},
users: [{type:mongoose.Schema.Types.ObjectId, ref: 'User'}]
});
这篇关于Mongoose 模式引用和未定义的类型“ObjectID"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!