MongoDB:如何在数据库中找到集合之间的关系

时间:2018-06-20 09:13:02

标签: mongodb mongoose mongoose-schema

我有一个user的集合,其中有id, firstName, lastNameid集合的user字段已在另一个集合中使用。

是否可以找到所有使用用户ID 的收藏集?

用户架构:

let userSchema = new mongoose.Schema({
  firstName: {
    type: String,
    trim: true,
    required: true
  },
  lastName: {
    type: String,
    trim: true,
    required: true
  }
},
{
  timestamps: true,
  usePushEach: true
});

培训模式:

var trainingSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  name: {type: String, required: true},
  institution: {
    instituteName: {type: String, required: true},
    type: {type: String, required: true},
    address: {
      country: String,
      state: String,
      city: String
    }
  },
  startDate: Date,
  endDate: Date,
  achievements: String,
  createdAt: Date,
  updatedAt: Date,
  endorsers: [{
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
    firstName: {
      type: String,
      required: true
    },
    lastName: {
      type: String,
      required: true
    },
    profilePic: {
      container: {type: String,default: null},
      name: { type: String, default: null }
    },
    currentPosition: {type: String,default: ""},
    currentWorkingCompany: {type: String,default: ""}
  }],
});

在上述架构中, userId 来自用户集合

注意:与MYSQL中可用的类似:

SELECT 
    ke.referenced_table_name 'parent table',
    ke.referenced_column_name 'parent column',
    ke.table_name 'child table',
    ke.column_name 'child column',
    ke.constraint_name
FROM
    information_schema.KEY_COLUMN_USAGE ke
WHERE
    ke.referenced_table_name IS NOT NULL
        AND table_schema = 'your_db_name'
ORDER BY ke.referenced_table_name;

来源:here

1 个答案:

答案 0 :(得分:0)

您可能需要名为join的MySQL函数。在MongoDB中,它名为$lookup,并且是aggregate函数的一部分。