我有一个带有Blog架构的Mongoose / Express应用程序,其他用户可以在其中“赞”博客。在“博客索引”中,我想按每个博客的喜欢次数排序。
在Blog架构中,我添加了一个名为noOfLikes的字段,但是我不确定如何在Blogs Controller(或其他地方)下实现计数,以允许我按noOfLikes对记录进行排序。
带有“喜欢”和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});
},
答案 0 :(得分:1)
查询执行后,您可以在没有猫鼬帮助的情况下对其进行排序。
例如:
<ItemGroup>
<FilesToExclude Include="$(OutputPath)\stats.json" />
<FilesToExclude Include="$(OutputPath)\deps.json" />
</ItemGroup>
<Target AfterTargets="build" Name="Exclude-Files">
<Delete Files="@(FilesToExclude)"/>
</Target>