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

相关内容

热门资讯

我来教大家“创思维激k透视源码... 大家好,今天小编来为大家解答创思维激k透视源码这个问题咨询软件客服可以免费测试直接加微信(13670...
记者揭秘“途游辅助软件”从来有... 途游辅助软件是一款专注玩家量身打造的游戏记牌类型软件,在途游辅助软件这款游戏中我们可以记录下每张牌的...
如何分辨真伪“江湖悠悠游戏辅助... 【亲,江湖悠悠游戏辅助 这款游戏可以开挂的,确实是有挂的,很多玩家在这款江湖悠悠游戏辅助中打牌都会发...
终于知道“花花生活圈辅助”往昔... 终于知道“花花生活圈辅助”往昔有辅助安装(有挂教程);无需打开直接搜索加薇136704302(咨询了...
信息共享“poker mast... 信息共享“poker master辅助”固有有开挂辅助工具(证实有挂)您好:poker master...
玩家必看秘籍“朋朋政和辅助器免... 朋朋政和辅助器免费在哪里是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可...
推荐一款“wepoker可以免... 推荐一款“wepoker可以免费玩吗”从来有开挂辅助下载(有挂解密)您好:wepoker可以免费玩吗...
今日焦点“新道游正版辅助微信辅... 今日焦点“新道游正版辅助微信辅助”往昔有辅助开挂平台(有挂攻略);无需打开直接搜索加(薇:13670...
玩家实测“桂林老k字牌免费安装... 桂林老k字牌免费安装是一款专注玩家量身打造的游戏记牌类型软件,在桂林老k字牌免费安装这款游戏中我们可...
分享开挂内幕“花花生活圈辅助”... 分享开挂内幕“花花生活圈辅助”往昔有辅助开挂软件(存在有挂);无需打开直接搜索加(薇:1367043...