簡體   English   中英

ZCCADCDEDB567ABAE643E15DCF0974E503Z Model 使用來自另一個模式的屬性查找

[英]Mongoose Model find using an attribute from anohter Schema

基本上我有2個模式。

用戶和帖子。

用戶有一個數組,其中包含來自帖子的 _ids。 並且 post 有一個屬性,告訴他是否是一個活躍的帖子。 -> is_active。 所以,我想過濾至少有一個活動帖子的用戶。

用戶模式

const UserSchema = new Schema(
  {
    name: {
      type: String,
      trim: true,
      required: true
    },
    posts: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Post'
      }
    ],
    created_at: {
      type: Date,
      required: true,
      default: Date.now()
    }
  }
)

export default mongoose.model<User>('User', UserSchema)

后架構

const postSchema = new Schema(
     {
       name: String,
       is_active: boolean
     }
  )

你可以試試這個:

Users.aggregate([
  {
    $lookup: {
      from: "Posts",
      let: { postIds: "$posts", },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $in: [ "$_id", "$$postIds" ]
                },
                {
                  $eq: [ "$is_active", true ]
                },
              ]
            }
          },
        },
        // You can remove the projection below 
        // if you need the actual posts data in the final result
        {
          $project: { _id: 1 }
        }
      ],
      as: "posts"
    }
  },
  {
    $match: {
      $expr: {
        $gt: [ { $size: "$posts" }, 0 ]
      }
    }
  }
])

你可以在這里的操場上測試它

我不確定您的應用程序的查詢要求,但您可以在 Posts 集合中的_idis_active屬性上添加 復合索引,以加快查詢速度。

您可以在此處閱讀有關 MongoDB 數據聚合的更多信息。

作為@Tunmee答案的替代方案

由於管道$lookup從 v3.6 開始可用,從 v4.2 開始仍然存在一些性能問題 您還可以使用 v3.2 中提供的“常規” $lookup

db.Users.aggregate([
  {
    $lookup: {
      from: "Posts",
      localField: "posts",
      foreignField: "_id",
      as: "posts"
    }
  },
  {
    $match: {
      "posts.is_active": true
    }
  }
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM