You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中如何从MongoDB获取最新评论并置顶显示?

实现最新评论显示在首位的解决方案

要让新添加的评论显示在首位,核心是从数据库查询评论时按创建时间倒序排列,以下是具体实现步骤:

修改查询逻辑

你的MongoDB文档已包含createdAt字段,直接基于该字段做倒序排序即可。在Comment.find()后追加.sort({ createdAt: -1 }),其中-1代表倒序排列,最新创建的评论会被优先返回。

修改后的完整代码

import db from "@/utils/db";
import Comment from "@/models/Comment";

const handler = async (req, res) => {
  await db.connect()

  if (req.method !== 'GET') {
    return 
  }
  
  // 按createdAt倒序查询评论
  const comments = await Comment.find({}).sort({ createdAt: -1 })

  // 修正判断逻辑:find方法返回空数组而非null
  if(comments.length === 0) {
    return res.status(200).json({
      message: 'Comment section is EMPTY!'
    })
  }

  res.status(200).send({ comments })
}

export default handler

补充说明

  • 若你的createdAt字段是通过Mongoose的timestamps: true自动生成的,该排序逻辑完全适配。
  • 也可通过_id字段实现排序:.sort({ _id: -1 }),因为MongoDB的ObjectId内置时间戳信息,倒序排列同样能让最新评论排在首位,效果与按createdAt排序一致。

内容的提问来源于stack exchange,提问作者erza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:57:06