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
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:
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:
This should solve your issue, and return the comments in the order from newest to oldest.
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.The
sort()
method is used on theComment.find({})
query to sort the comments based on thecreatedAt
field in descending order (-1
indicates descending order). This ensures that the latest comments will appear at the beginning of thecomments
array.