首页 > 解决方案 > Mongoose/Express - 计算点赞数

问题描述

我有一个带有博客架构的 Mongoose/Express 应用程序,其他用户可以在其中“喜欢”这些博客。在博客索引中,我想按每个博客的点赞数排序。

在博客架构中,我添加了一个名为 noOfLikes 的字段,但我不确定如何在博客控制器(或其他地方)下实现计数以允许我按 noOfLikes 对记录进行排序。

带有 likes 和 noOfLikes 字段的博客模式(为简单起见,删除了其他字段):

let blogSchema = new mongoose.Schema({
   comments: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Comment"
      }   
   ],
   likes: [
      {
          type: mongoose.Schema.Types.ObjectId,
          ref: "User"
      }
   ],
   noOfLikes: { type: Number, default: 0 },
});

module.exports = mongoose.model("Blog", blogSchema);

博客控制器,按 noOfLikes 排序当前无法正常工作,因为不确定如何在控制器中实现点赞计数:

    async blogIndexAll (req, res, next) {

        blogs = await Blog.find().sort({ 'noOfLikes': -1 });

        res.render("blogViews/blog", {blogs, cloudinary, currentUser: req.user});
    },

标签: node.jsmongodbmongoose

解决方案


执行查询后,您可以在没有猫鼬帮助的情况下对其进行排序。

例如:

blogs = await Blog.find({}).exec();
// Using Array.prototype.sort
blogs = blogs.sort( (a,b) => b.likes.length - a.likes.length );

推荐阅读