如何在mongodb中获取关系数据?

时间:2018-09-06 05:55:17

标签: node.js mongodb

我有3个方案Project,Consultant,Client,我已将项目顾问和项目分配给客户。像这样存储

client: {
     name: ABC,
     consultants: [
        {
           consultantId: "1",
           projectId: "1",
           "start": "Some Date",
           "end": "Some Date",
        },
        {
           consultantId: "2",
           projectId: "2",
           "start": "Some Date",
           "end": "Some Date",
        }, .....
     ]
    }

获取所有客户的列表时,包括分配给客户的顾问,并且获取ID而不是顾问和项目的名称。如何在表之间建立关系?

const clientsSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    consultants: [
      {
        consultantId: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "consultants",
        },
        projectId: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "projects",
        },
        start_date: {
          type: Date,
          index: true,
        },
        end_date: {
          type: Date,
          index: true,
        },
      },
    ],
  },
  {
    timestamps: true,
  },
);

const Clients = (module.exports = mongoose.model("Clients", clientsSchema));

0 个答案:

没有答案