我的 Post Controller 上有一个 getPosts Controller ,我的目标是按 createdAt 时间对它进行排序以保持顺序,因为当我将它映射到前端时,它是从最后创建的开始到最新创建的。
const getPosts = asyncHandler(async (req, res) => {
const posts = await Post.find().sort([createdAt, 1]);
res.json(posts);
});
最佳答案
sort() 不能接受数组,它接受字符串或对象
const posts = await Post.find().sort({createdAt: 1});
您也可以使用"asc ","ascending "代替1。
关于javascript - Mongoose 按 createdAt 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67264632/