使用anohter模式中的属性查找猫鼬模型

时间:2020-07-27 19:54:25

标签: javascript node.js mongodb mongoose

基本上我有2个模式。

用户和帖子。

用户有一个数组,其中包含帖子中的_id。 帖子具有一个属性,可以判断他是否为活动帖子。 -> is_active。 因此,我要过滤至少有一个活跃帖子的User。

UserSchema

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

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

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的更多信息。

答案 1 :(得分:0)

替代@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
    }
  }
])