javascript – Mongoose模式引用和未定义类型’ObjectID’

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

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 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'}]
});
上一篇:MongoDB中的JavaScript NoSQL注入预防


下一篇:JavaScript-没有字段名称的猫鼬结构聚合输出