如何使用 mongodb 聚合获取所有以下帖子?

问题描述 投票:0回答:0

我有以下收藏

_id:objectId('643668e0beaf5f41fdd19cf0')
userId:objectId('6436649f15da05f1398e4935')
followings:[64364fa540eb588f9a424939]
}

和邮寄

userId:objectId('64364fa540eb588f9a424939')
other data fields

使用下面的给定代码,我得到了以下列表,它工作正常

 const followings = await this.followingService.getFollowingIds(
            data.userId,
          );
          const followingsArray = [];
          followings.forEach((obj) => {
            followingsArray.push(obj.followings);
          });
          const r = followingsArray.flat();

但是当我尝试将 followingsArray 中的 id 与 userId 匹配并获取与 followingsArray 中的 id 匹配的所有帖子时,此代码返回空数组

const re = await this.socialPostModel
            .aggregate([
              {
                $project: {
                  _id: 1,
                  userId: 1,
                  location: 1,
                  caption: 1,
                  postAudiencePreference: 1,
                  postType: 1,
                  media: 1,
                  likesCount: 1,
                  commentCount: 1,
                  createdAt: 1,
                  voucherId: 1,
                  updatedAt: 1,
                  followingsArray: r,
                },
              },
              {
                $unwind: '$followingsArray',
              },
              {
                $match: {
                  userId: '$followingsArray',
                 
                },
              },
            ])
            .skip(offset)
            .limit(limit);
          console.log('re = ', re);

但是如果我像这样用 userId 替换匹配阶段的“$followingsArray”

userId: new mongoose.Types.ObjectId(
                    '64364fa540eb588f9a424939',
                  ),

它给了我帖子。我不明白为什么会这样。谁能帮帮我?

node.js mongodb mongodb-query aggregation-framework aggregate
© www.soinside.com 2019 - 2024. All rights reserved.