【问题标题】:How to lookup into same collection in an array of id?如何在 id 数组中查找相同的集合?
【发布时间】:2021-04-28 08:27:55
【问题描述】:

我有一个用户架构

var userSchema = new mongoose.Schema(
{
  username: {
    type: String,
    required: true,
  },
  follows : [{
    type : Schema.Types.ObjectId, 
    ref : "User"
  }],
  followers : [{
    type : Schema.Types.ObjectId, 
    ref : "User"
  }],
});

我有一个userId,然后我想从该用户 ID 中获取所有关注者。我是 mongodb 的新手。

所以一个用户有一个followers[]字段,它会包含所有follower的userid。所以我想获取关注者的所有字段。

【问题讨论】:

    标签: arrays mongodb mongoose aggregate lookup


    【解决方案1】:

    虽然关注者指的是用户对象 id,所以最好在 userSchema 中使用 find 方法。 假设您将 Id 作为参数传递,然后只需 find 方法。

    const fields = await userSchema.find({ follower: req.params.id });
    

    【讨论】:

    • 其实我想找到folwers的详细信息follower的名字,username他的id。如果他是我的追随者。我只有我的身份证。我想获取每个关注者的所有详细信息
    • 好吧。你有你的追随者吗?如果是,那么只需映射该追随者对象并通过映射访问每个项目。这只是 javascript 的逻辑思维。
    【解决方案2】:
    • $match你的用户ID条件
    • $lookup 加入,在from 中传递相同的集合名称
    User.aggregate([
      { $match: { _id: 1 } },
      {
        $lookup: {
          from: "user", // update to your actual collection name
          localField: "followers",
          foreignField: "_id",
          as: "followers"
        }
      }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多