skip to Main Content

I am building comment app. Problem I am facing is latest post/comment is on bottom. I would like to add new comment to first position.
Can you please tell me how to do it? Thank you.

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

const handler = async (req, res) => {

  await db.connect()

  if (req.method !== 'GET') {
    return 
  }
  
  const comments = await Comment.find({})

  if(!comments) {
    return res.status(200).json({
      message: 'Comment section is EMPTY!'
    })
  }

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

export default handler

my mongodb database is looking like this:


_id: 646be098d2de11097a4b62d6
user: 646bc68e673a78c472646e5e
userName:"john"
comment:"ffffffffffffffff"
like:0
createdAt:2023-05-22T21:37:28.018+00:00
updatedAt:2023-05-22T21:37:28.018+00:00

2

Answers


  1. You can sort the data you get from MongoDB to sort the comments by their creation date. You use the sort() method in your query and pass it an object that specifies how you want the data to be sorted. If you want the most recent comments to appear first, you sort by the CreateAt field in descending order.

    You can do this like this:

    const comments = await Comment.find({}).sort({ createdAt: -1 })
    

    In this line of code, the expression sort({createAt: -1 }) means it will sort the comments by the CreatedAt field in descending order. That way, the most recent comments (the ones with the createAt timestamp later) come first.

    Here is your updated code:

    import db from "@/utils/db";
    import Comment from "@/models/Comment";
    
    const handler = async (req, res) => {
    
      await db.connect()
    
      if (req.method !== 'GET') {
        return 
      }
      
      const comments = await Comment.find({}).sort({ createdAt: -1 })
    
      if(!comments) {
        return res.status(200).json({
          message: 'Comment section is EMPTY!'
        })
      }
    
      res.status(200).send({ comments })
    }
    
    export default handler
    

    This should solve your issue, and return the comments in the order from newest to oldest.

    Login or Signup to reply.
  2. To add new comments to the first position, you need to modify your code to sort the comments in descending order based on the creation date (createdAt) before sending the response.

     import db from "@/utils/db";
        import Comment from "@/models/Comment";
        
        const handler = async (req, res) => {
          await db.connect();
        
          if (req.method !== 'GET') {
            return;
          }
        
          const comments = await Comment.find({}).sort({ createdAt: -1 });
        
          if (!comments || comments.length === 0) {
            return res.status(200).json({
              message: 'Comment section is EMPTY!'
            });
          }
        
          res.status(200).send({ comments });
        };
        
        export default handler;
    

    The sort() method is used on the Comment.find({}) query to sort the comments based on the createdAt field in descending order (-1 indicates descending order). This ensures that the latest comments will appear at the beginning of the comments array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search