Sorting with mongoose - find()

I have a Model with {timestamps : true}.
I want that every time i create a new post it will show at the top of the page. I tried with .sort (createdAt: -1) but it didn’t work. Pls help and thankyou guys
Screenshot 2022-04-18 145700

Hi,

Your query seams good.

Can you check in the database if createdAt properties are added to the documents?

Also, you can actually do the sorting with _id if it’s of the type ObjectId:

Model.find().sort({ _id: -1 })

I checked the database, the prop createdAt already added but something wrong with my database, it shows only one data even though i don’t use any query. As before, a list will be displayed.
And i tried sort with _id, same result. when i create a new post, it still shows at the end of the array

Hi,

Then the issue is not with sort. You have only one document inside the collection, so only that document will be returned.

You should add more new documents and then check if the sort is working. :smiley:

You can see that Total Document is 7 - My posts alredy have 7 post diffirent ~.~

But wait, you added limit(1) to the query, right? That is why you have only one document returned.