如何在 id 数组中查找相同的集合?

How to lookup into same collection in an array of id?

我有一个用户架构

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,然后我想从该 useriD 中获取所有关注者。我是 mongodb.

的新手

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

因为关注者引用了用户对象 ID,所以最好在 userSchema 中使用 find 方法。 假设您将 Id 作为参数传递,然后只需查找方法。

const fields = await userSchema.find({ follower: req.params.id });
  • $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