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

16

我正在尝试在我的模式之间建立一些关系,但是我的解决方案有一些问题。 这是我的设备模式:

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抛出错误

类型错误: 未定义类型 ObjectIDroom。您尝试过嵌套模式吗?您只能使用引用或数组进行嵌套。

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

1个回答

31

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'}]
});

3
使用 mongoose.Schema.Types.ObjectId 可以正常工作。奇怪的是,使用 mongoose.Types.ObjectId 我能够创建用户对象和设备对象,并且在它们之间建立关联。当我添加第二个模型(房间)并在房间和设备之间建立关联时,出现了错误。 - niba

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接