【问题标题】:Mongoose schema reference and undefined type 'ObjectID'Mongoose 架构引用和未定义类型“ObjectID”
【发布时间】:2015-04-21 11:19:38
【问题描述】:

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

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

TypeError: Undefined type ObjectID at room 你尝试过嵌套吗 模式?您只能使用 refs 或数组进行嵌套。

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

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

    【讨论】:

    • 使用mongoose.Schema.Types.ObjectId 可以正常工作。奇怪的是,使用mongoose.Types.ObjectId 我能够创建用户对象和设备对象并在它们之间建立关系。当我添加第二个模型(房间)并在房间和设备之间建立关系时显示错误
    猜你喜欢
    • 2014-09-14
    • 2017-07-17
    • 2021-11-23
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2019-03-18
    • 1970-01-01
    相关资源
    最近更新 更多