2

嗨,我想建立一个排行榜,根据用户在所有帖子中积累的点赞数对用户进行排名。

我的帖子数据库

  user: {
    type: Schema.Types.ObjectId,
  },
  text: {
    type: String,
    required: true,
  },
  imageURL: {
    type: [String],
  },
  name: {
    type: String,
    required: true,
  },
  category: {
    type: String,
  },
  likes: [
    {
      user: {
        type: Schema.Types.ObjectId,
      },
    },
  ],
  date: {
    type: Date,
    default: Date.now,
  }

我的用户数据库:


  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },

我尝试了各种查询和聚合函数,但我无法为此找到正确的解决方案。有没有其他方法可以获取列表。我想获得一个用户列表以及他们在所有帖子中获得的总喜欢。我怎样才能做到这一点 ?

4

2 回答 2

2

你可以试试这个查询

db.collection.aggregate([
  {
    $project: {
      user: 1,
      numberOfLikes: {
        $cond: {
          if: {
            $isArray: "$likes"
          },
          then: {
            $size: "$likes"
          },
          else: "NA"
        }
      }
    }
  }
])

您可以在此处找到此查询的演示

于 2020-06-08T16:22:25.447 回答
0

我最近有同样的情况,这是我解决它的方法:

我创建了 3 个不同的模型。用户,帖子,喜欢。Post 模型将是:

 user: {
    type: Schema.Types.ObjectId,
  },
  text: {
    type: String,
    required: true,
  },
  imageURL: {
    type: [String],
  },
  name: {
    type: String,
    required: true,
  },
  category: {
    type: String,
  },
  date: {
    type: Date,
    default: Date.now,
  }

喜欢模型:

postId: {
  type: Schema.Types.ObjectId,
  required: true
},
userId: {
  type: Schema.Types.ObjectId,
  required: true
},
likedBy: {
  type: Schema.Types.ObjectId,
  ref: 'User',
  required: true,
}
  1. 在获取帖子时,您可以使用聚合函数并使用帖子获取喜欢,如下所示
  2. 如果您想获取用户收到的赞数,您可以通过以下方式轻松完成:Like.find({userId}).countDocuments()

在这种情况下避免使用数组。因为用户喜欢没有限制。如果您的应用程序增长,以这种方式管理喜欢将是一场噩梦。

于 2020-06-08T16:25:22.227 回答