Mongoose sorting by createdAt

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);
});

Answer

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.