【问题标题】:How to define a single reference schema using mongoose如何使用 mongoose 定义单个参考架构
【发布时间】:2014-06-28 03:03:00
【问题描述】:

我是 node.jsmongodb 的新手,并且在下面的代码中,我在部门的表员工中定义了一个引用,但是当我从这里插入或获取数据时员工表我总是以数组格式获取,但我想将引用定义为单列而不是多列

var employee = new mongoose.Schema({
    name: String,
    dept: [department]
});

var department = new mongoose.Schema({
     dept_name : String,
     dept_code : String
})

我想要来自员工表的响应数据,格式为 `{"name":"CS",dept:{"id":_id_of_dept}}

请指导我实现目标的正确方法。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您只能使用引用或数组进行嵌套,因此在此示例中,您可以创建 department 记录并在 employee 文档中引用该记录,或者为 employee 创建一个 departments 数组(我知道这不是你想要做的)。

    要从您的 employee 引用 department 文档,您可以使用以下内容:

    var department = new mongoose.Schema({
        dept_name : String,
        dept_code : String
    });
    
    mongoose.model('Department', department);
    
    var employee = new mongoose.Schema({
        name: String,
        dept: { type: Schema.Types.ObjectId, ref: 'Department' }
    });
    

    但是,在查询您的 employee 以收集 department 数据时,您需要 populate

    但在高层次上,看看您要完成的工作,我建议直接将department 存储在employee 文档中。关系数据库可能通常以您上面描述的模式结束,但在基于文档的数据库中,将departmentemployee 分开确实没有很好的理由。执行我在下面提出的操作将有助于您将来查询和一般访问数据:

    var employee = new mongoose.Schema({
        name: String,
        dept: {
            dept_name : String,
            dept_code : String
        }
    });
    

    This answer might be helpful in understanding what I mean.

    【讨论】:

    • 感谢 @dylants 提供 mongodb 的非关系模式。但我在我的应用程序中需要它。如果我按照您的建议更改了我的架构,但是在我填充部门字段时出现了一些问题。它说该引用未被识别,但是当我按照上面的示例更改引用时(在 [] 内)。它工作正常。但我不想要多种形式。
    猜你喜欢
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2014-09-14
    • 2016-03-31
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    相关资源
    最近更新 更多