按照关系字段的计数对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')查询帖子,并根据评论计数字段进行降序排序。这将返回一个按照评论计数排序的帖子数组。

相关内容

热门资讯

玩家爆料"宁波同乐游... 玩家爆料"宁波同乐游辅助下载"开挂(透视)辅助透视有挂神器-详细教程《详细加薇136704302咨询...
四分钟辅助“小闲辅助器”开挂(... 小闲辅助器开挂教程视频分享装挂详细步骤在当今的网络游戏中,小闲辅助器作为一种经典的娱乐方式,吸引了无...
解密关于"约局吧德州... 约局吧德州真的存在透视吗 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理...
七分钟辅助“爱趣玩辅助”开挂(... 七分钟辅助“爱趣玩辅助”开挂(脚本)辅助脚本教你攻略-了解有挂您好:爱趣玩辅助这款游戏可以开挂,确实...
玩家爆料"温州茶苑手... 玩家爆料"温州茶苑手机版辅助器"开挂(神器)辅助神器有挂总结-微扑克教程 >>您好:软件加薇1367...
开挂辅助“789大菠萝如何手气... >>您好:789大菠萝如何手气顺确实是有挂的,很多玩家在这款789大菠萝如何手气顺游戏中打牌都会发现...
透视好牌"新西部微信... 透视好牌"新西部微信辅助"开挂(透视)辅助透视真的有挂-2026新版 了解更多开挂安装加(13670...
一分钟辅助“佛手在线13道辅助... 一分钟辅助“佛手在线13道辅助”开挂(工具)辅助工具新2026版-有挂技巧您好:佛手在线13道辅助这...
实测分享"如何下载科... 实测分享"如何下载科乐填大坑辅助器"开挂(软件)辅助软件的确有挂-透牌教程;亲,如何下载科乐填大坑辅...
七分钟辅助“微乐家乡游戏攻略”... 七分钟辅助“微乐家乡游戏攻略”开挂(透视)辅助透视切实教程-有挂讲解>>您好:软件加薇1367043...