首页 > 解决方案 > MongoDB:如何查找数据库中集合之间的关系

问题描述

我有一个集合,user其中有id, firstName, lastName. id集合字段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;

来源:这里

标签: mongodbmongoosemongoose-schema

解决方案


您可能需要名为 join 的 MySQL 函数。在 MongoDB 中,它被命名为$lookup,它是聚合函数的一部分。


推荐阅读