如何聚合ObjectId数组

时间:2019-12-20 12:46:03

标签: node.js mongodb mongoose aggregation-framework

我有两个MongoDB集合。组织集合和小组集合。 每个组都有对组织的引用,每个组织都有对组的引用数组。

const GroupSchema: Schema = new Schema({
  label: {
    type: String,
    required: true
  },
  organization: {
    type: Types.ObjectId,
    ref: "Organization"
  },
  users: [{
    type: Types.ObjectId,
    ref: "Users"
  }],
  controllers: [{
    type: Types.ObjectId,
    ref: "Controllers"
  }],
}, {timestamps: true} )
const OrganizationSchema: Schema = new Schema({
  title: {
    type: String,
    require: true
  },
  location: {
    city: {
      type: String,
    }
  },
  groups: [{
    type: Types.ObjectId,
    ref: "Groups"
  }],
  users: [{                       
    type: Types.ObjectId,
    ref: "Users"
  }],
}, {timestamps: true});

我使用聚合mongodb框架。

现在我们正在解决我的问题:)

如何从组织机构获取所有信息?包括嵌套集合。 在分组中,我按控制器和用户的集合排列了一系列引用。


const infoAboutOrganization = await IOrganizations.aggregate([
      {
        $match : { "_id": Types.ObjectId(id) }
      },
      {
        $lookup:  {
          from: "users",
          localField: "_id",
          foreignField: "organization",
          as: "users"
        }
      },
      {
        $lookup:  {
          from: "groups",
          localField: "_id",
          foreignField: "organization",
          as: "groups"
        }
      },
      { $project: { "users.salt": false } },
      { $project: { "users.hashed_password": false } },
    ]);

enter image description here

enter image description here

0 个答案:

没有答案