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
>Solution :
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.