Mongoose模式引用和未定义类型'ObjectID'

nib*_*iba 13 javascript mongoose mongodb node.js

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

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

这里的房间架构:

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

猫鼬抛出错误

类型错误:未定义的类型ObjectID,在room 你尝试筑巢的架构?您只能使用refs或数组进行嵌套.

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

Joh*_*yHK 29

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'}]
});
Run Code Online (Sandbox Code Playgroud)

  • 使用`mongoose.Schema.Types.ObjectId`它正在工作.奇怪的是,使用`mongoose.Types.ObjectId`,我能够创建用户对象和设备对象,并在它们之间建立关系.当我添加第二个模型(Room)并在Room和Device之间建立关系时显示错误 (3认同)