Mongoose sorting by createdAt

Viewed 1980

I have a getPosts controller on my Post Controller, my goal is to sort it by the createdAt time to maintain order because when I map it on the frontend it starts from the last created to the latest.

const getPosts = asyncHandler(async (req, res) => {
  const posts = await Post.find().sort([createdAt, 1]);
  res.json(posts);
});
3 Answers

sort() can't take arrays it either takes string or an object

const posts = await Post.find().sort({createdAt: 1});

also you can use " asc "," ascending " instead of 1.

You can use mongo query sort() to get that. It can take value 1 or -1 according to sorting order, you can read mongo db document for more here.

Also you can put this sort query in timestamp of these for getting this too.

//Sorting by descending order
const posts = await Post.find().sort({ createdAt: -1 })

//Sorting by ascending order
const posts = await Post.find().sort({ createdAt: 1 })

So you can do this:

const getPosts = asyncHandler(async (req, res) => {
  const posts = await Post.find().sort({ createdAt: 1 })
  res.json(posts)
})

sort() takes in either an Object or a String.

the correct syntax should be

 const posts = await Post.find().sort({createdAt: 1});
Related