首页 > 解决方案 > 按在 Mongoose 中创建的日期对引用的 Schema 进行排序

问题描述

以下问题,在我的应用程序中,我有帖子,每个帖子都可以有一系列评论。我正在尝试按日期对评论进行排序。我已经搜索并尝试了任何解决方案,但没有一个对我有用。

我的尝试不起作用:

const post = await Post.findById(id)
    .populate({
        path: 'comments',
        options: { sort: { createdAt: -1 } },
    })

const post = await Post.findById(id)
        .sort({ 'comments.createdAt': -1 })

如果在我的帖子模型中引用评论模型,如下所示:

评论模式

    {
        comment: { type: String, required: true },
        user: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'User',
        },
    },
    { timestamps: true }
)

后模型:

const postSchema = mongoose.Schema(
    {
        user: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'User',
        },
        image: {
            type: String,
        },
        text: {
            type: String,
            required: true,
        },
        workout: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Workout',
        },
        comments: [commentSchema],
        numComments: {
            type: Number,
            required: true,
            default: 0,
        },
        likes: [likeSchema],
        numLikes: {
            type: Number,
            required: true,
            default: 0,
        },
    },
    {
        timestamps: true,
    }
)

感谢您提前提供任何帮助

标签: javascriptnode.jsmongodbmongoose

解决方案


问题是您要在哪里排序,在客户端对其进行排序,最简单的解决方案是对数组进行排序comments,因为您没有引用另一个ref不需要populate(查找)的模式文档,只需编写另一个then函数,例如这个:

    const post = await Post.findById(p._id).then(result => {
        result.comments.sort((a, b) => a.createdAt > b.createdAt ? -1 : 1);
        return result;
    })

要在获取时排序,您应该使用聚合模型函数,并使用管道阶段的模式:$match、$unwind、$sort、$group。但这是一种复杂的方式。


推荐阅读