【问题标题】:Using aggregate and lookup with Mongoose在 Mongoose 中使用聚合和查找
【发布时间】:2021-09-03 17:40:08
【问题描述】:

我有一个用户模式,它有一个名为 associatedTeams 的键。 它看起来像这样:

export const UserSchema = new Schema({
  associatedTeams: [AssociatedTeamSchema],
});

同时,关联团队架构如下所示:

export const AssociatedTeamSchema = new Schema({
  teamId: { type: ObjectId, required: true }, // each id will be a Team document
  userIsAdmin: { type: Boolean, required: true },
});

最后,Team Schema 如下所示:

const TeamSchema = new Schema(
    players: [
      {
        type: ObjectId, // each will be a User
      },
    ],
);

如何编写操作以从所有关联团队中删除已删除的用户? 现在我只是在尝试访问所有相关团队。我很确定我可以使用聚合语法来做到这一点,但我不确定具体如何。

大概是这样的:

const teams = await UserInfo.aggregate({
    $lookup: {
      from: Team.collection.name,
      local_field: "associatedTeams.teamId",
      foreign_field: "_id",
      as: "teams",
    },
  });

我非常感谢任何帮助。问题是我不知道如何引用每个关联团队中的“teamId”字段。非常感谢您的帮助。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    你应该使用两个$lookup首先获取AssociatedTeam的数据,然后再获取team

    const teams = await UserInfo.aggregate([{
        $lookup: {
          from: Team.collection.name, // AssociatedTeamCollection
          local_field: "associatedTeams",
          foreign_field: "_id",
          as: "associatedTeams",
        },
      },
        $lookup: {
          from: Team.collection.name, // teamCollection
          local_field: "associatedTeams.teamId",
          foreign_field: "_id",
          as: "team",
        },
      }
    ]);
    

    【讨论】:

    • 谢谢,我试试看
    • 遗憾的是这不起作用。有没有办法在 Team 模型上使用 updateMany 操作来实现我想要的?
    • 您能否更新您的问题,添加每个架构的示例数据和您的输出预期数据?
    【解决方案2】:

    这是我的答案。希望这可以帮助某人:

    const UserInfo = mongoose.model("UserInfo") as IUserModel;
      const Team = mongoose.model("Team");
    
      // in each of the user's associated teams, I want to remove the user from
      // that team's players
     
      // for some weird reason I couldn't access the user document with 'this'
    
      const user = await UserInfo.findById(this._id);
      const ids = user.associatedTeams.map((team) => team.teamId);
    
      await Team.updateMany(
        { _id: { $in: ids } },
        { $pull: { players: this._id, admins: this._id } }
      );
    
      next();
    

    【讨论】:

      猜你喜欢
      • 2018-04-04
      • 2017-07-12
      • 2020-04-23
      • 2019-02-03
      • 2020-07-16
      • 2021-01-22
      • 1970-01-01
      • 2019-01-21
      • 2019-06-22
      相关资源
      最近更新 更多