按照关系字段的计数对KeystoneJS结果进行排序
创始人
2024-08-24 04:30:01
0

在KeystoneJS中,可以使用.populate()方法来按照关系字段的计数对结果进行排序。下面是一个示例代码:

const keystone = require('keystone');
const { Types } = keystone.Field;

// 定义模型
const Post = keystone.List('Post', {
    map: { name: 'title' },
    autokey: { path: 'slug', from: 'title', unique: true },
});

const Comment = keystone.List('Comment', {
    map: { name: 'content' },
});

Post.add({
    title: { type: Types.Text, required: true },
    commentsCount: { type: Types.Number, default: 0, noedit: true },
});

Comment.add({
    content: { type: Types.Text, required: true },
    post: { type: Types.Relationship, ref: 'Post', refPath: 'comments' },
});

// 在模型上注册一个中间件,用于更新评论计数字段
Comment.schema.post('save', async function () {
    const postId = this.post;
    const count = await Comment.model.countDocuments({ post: postId });
    await Post.model.findByIdAndUpdate(postId, { commentsCount: count });
});

// 查询帖子,并按照评论计数字段降序排序
Post.model.find()
    .populate('comments')
    .sort('-commentsCount')
    .exec((err, posts) => {
        if (err) {
            console.error(err);
        } else {
            console.log(posts);
        }
    });

在这个示例中,我们有两个模型:PostCommentPost模型有一个commentsCount字段,用于存储与该帖子相关联的评论计数。Comment模型有一个post字段,用于关联到Post模型。

Comment模型的schema中,我们注册了一个post('save')中间件,用于在每次保存评论时更新对应帖子的评论计数字段。这样,无论是添加、更新还是删除评论,都能保持评论计数字段的准确性。

最后,我们使用Post.model.find().populate('comments').sort('-commentsCount')查询帖子,并根据评论计数字段进行降序排序。这将返回一个按照评论计数排序的帖子数组。

相关内容

热门资讯

第7分钟透视!微乐小程序黑科技... 您好,微乐小程序黑科技这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩...
无独有偶!微乐小程序黑科技,微... 无独有偶!微乐小程序黑科技,微信小程序辅助器免费版(透视)果然真的有挂(哔哩哔哩)1、金币登录送、破...
八分钟透视!微乐小程序免费黑科... 八分钟透视!微乐小程序免费黑科技,微乐小程序自建房辅助器(开挂)一直真的是有挂(2026)该软件可以...
透视总结!微乐小程序黑科技,微... 透视总结!微乐小程序黑科技,微信小程序有挂吗辅助(透视)果然真的是有挂(哔哩哔哩)1、全新机制【微信...
一直以来!微乐小程序免费黑科技... 一直以来!微乐小程序免费黑科技,微信小程序微乐辅助器破解版(透视)一直是真的挂(哔哩哔哩)1、下载好...
第1分钟教程!微乐小程序免费黑... 第1分钟教程!微乐小程序免费黑科技,微信微乐辅助ios(开挂)真是是真的挂(2026)1、下载好微乐...
第1分钟下载!微乐小程序黑科技... 第1分钟下载!微乐小程序黑科技,微乐小程序辅助工具免费版(开挂)确实真的有挂(2026)一、微乐小程...
明白辅助挂!微乐小程序黑科技,... 明白辅助挂!微乐小程序黑科技,微乐小程序辅助工具哪里下载(透视)竟然存在有挂(哔哩哔哩)1、玩家可以...
9分钟开挂!微乐小程序免费黑科... 9分钟开挂!微乐小程序免费黑科技,微乐多乐跑作弊(开挂)一直真的是有挂(2026)微乐小程序免费黑科...
透视透视挂!微乐小程序免费黑科... 透视透视挂!微乐小程序免费黑科技,微乐自建房怎么提高胜率(透视)一贯真的有挂(哔哩哔哩)1、玩家可以...