node.js - 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});
},
解决方案
执行查询后,您可以在没有猫鼬帮助的情况下对其进行排序。
例如:
blogs = await Blog.find({}).exec();
// Using Array.prototype.sort
blogs = blogs.sort( (a,b) => b.likes.length - a.likes.length );
推荐阅读
- c - 从不兼容的指针类型 [-Wincompatible-pointer-types] 类型传递“HAL_I2C_Master_Transmit”的参数 3
- markdown - Pandoc:在 SubTOC 中拆分 TOC
- python - 如何将已读取并解析的数据写入另一个文件?
- angular - 如何在使用 Angular 开发的整个应用程序中访问用户名?
- node.js - 如何通过 git bash 命令行将全栈(ReactJS、NodeJS、socketIO)项目上传到 github
- unity3d - 打包虚幻游戏后阻止显示电影文件
- python - 将 Python 时间转换为 MicroPython PyBoard
- python - Python 属性错误:“int”对象没有属性“reshape”
- python - 当字段来自许多表 FK 时,Django 序列化程序出现问题
- javascript - Javascript 的 ASP Gridview“全选”问题