【问题标题】:Mongoose Model find using an attribute from anohter Schema猫鼬模型使用来自另一个模式的属性查找
【发布时间】:2020-07-28 07:02:41
【问题描述】:

基本上我有 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
     }
  )

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    作为@Tunmee 的answer 的替代品

    由于管道 $lookup 从 v3.6 开始可用,并且从 v4.2 开始仍有一些性能 issues。您还可以使用 v3.2 中提供的“常规”$lookup

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

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      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 ]
            }
          }
        }
      ])
      

      你可以在操场上测试一下here

      我不确定您的应用程序的查询要求,但您可以在 Posts 集合中的 _idis_active 属性上添加 compound index 以加快查询速度。

      您可以阅读有关 MongoDB 数据聚合的更多信息here

      【讨论】:

      • 谢谢!!!这对我有用。谢谢你带我看Mongo Playground。这对我来说是一个发现:)
      猜你喜欢
      • 2018-06-08
      • 2021-08-17
      • 2015-02-23
      • 2020-01-05
      • 1970-01-01
      • 2021-05-24
      • 2011-11-14
      • 1970-01-01
      • 2015-05-15
      相关资源
      最近更新 更多