代码之家  ›  专栏  ›  技术社区  ›  Thamaraiselvam

如何在MongoDB中关联两个集合

  •  0
  • Thamaraiselvam  · 技术社区  · 6 年前

    我已经创建了两个集合 供应商和员工 供应商集合具有员工的引用“ 雇员ID:[字符串] 我也应该这么做吗?那是个好主意吗?在两个集合中添加引用?

    如果我想让所有员工都写上他们的公司名称呢?我很困惑。

    雇员

    const employeeSchema = Schema({
      _id: Schema.Types.ObjectId,
      name: String,
      address: String,
      email: String,
      designation: String,
      contact_number: Number,
      contract_start: Date,
      contract_end: Date
    });
    

    小贩

    const vendorSchema = Schema({
        _id: Schema.Types.ObjectId,
        name: String,
        address: String,
        email: [String],
        contact_number: [Number],
        contract_start: Date,
        contract_end: Date,
        emplyoee_id:[String]
    });
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   robertsLando    6 年前

    在Mongoose模型中,可以使用对另一个模型的引用来定义属性。检查猫鼬 popolate

    例子:

    
    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const personSchema = Schema({
      _id: Schema.Types.ObjectId,
      name: String,
      age: Number,
      stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
    });
    
    const storySchema = Schema({
      author: { type: Schema.Types.ObjectId, ref: 'Person' },
      title: String,
      fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
    });
    
    const Story = mongoose.model('Story', storySchema);
    const Person = mongoose.model('Person', personSchema);
    
    
        2
  •  0
  •   Ashwanth Madhav    6 年前

    对于环回框架

    我已经用环回框架完成了。例如,用户集合和项目集合对每个用户都有,可以有多个项目,每个项目只有一个用户。

    在项目模型中

    "relations": {
       "user": {
       "type": "belongsTo",
       "model": "user",
       "foreignKey": "id"
    }}
    

    在用户模型中

    "relations": {
      "projects": {
      "type": "hasMany",
      "model": "project",
      "foreignKey": "project_user_id"
    }}