猫鼬模式引用和未定义类型"ObjectID" [英] Mongoose schema reference and undefined type 'ObjectID'

查看:72
本文介绍了猫鼬模式引用和未定义类型"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:room处的未定义类型ObjectID您是否尝试过嵌套 模式?您只能使用引用或数组进行嵌套.

TypeError: Undefined type ObjectID at room 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.ObjectIdObjectId构造函数,要在模式定义中使用的是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'}]
});

这篇关于猫鼬模式引用和未定义类型"ObjectID"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆