【问题标题】:How to relate two collections in MongoDB如何在 MongoDB 中关联两个集合
【发布时间】:2019-07-18 13:50:39
【问题描述】:

我创建了两个集合vendor 和employeevendor 集合有员工“emplyoee_id:[String]”的引用 我应该反之亦然吗?这是个好主意吗?在两个集合中添加引用?

如果我希望所有员工都附上公司名称怎么办?我很困惑。

员工

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

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongoose-schema


    【解决方案1】:

    对于环回框架

    我已经用 Loopback 框架完成了。例如 User collection 和 Project collection has taken 对于每个用户,可以有多个项目,每个项目只有一个用户。

    在项目模型中

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

    在用户模型中

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

    【讨论】:

      【解决方案2】:

      在猫鼬模型中,您可以使用对另一个模型的引用来定义属性。检查猫鼬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);
      
      

      【讨论】:

      • 谢谢,您将我重定向到正确的路径并节省了我的时间 +1
      猜你喜欢
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      • 2020-01-31
      • 2017-08-10
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      相关资源
      最近更新 更多