[英]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.我在我的帖子 Controller 上有一个 getPosts controller,我的目标是按 createdAt 时间对其进行排序以维持秩序,因为当我在前端创建 map 时,它从最新开始。
const getPosts = asyncHandler(async (req, res) => {
const posts = await Post.find().sort([createdAt, 1]);
res.json(posts);
});
sort() can't take arrays it either takes string or an object sort() 不能采用 arrays 它要么采用字符串要么采用 object
const posts = await Post.find().sort({createdAt: 1});
also you can use " asc " , " ascending " instead of 1.您也可以使用“asc” 、 “ascending”而不是 1。
You can use mongo query sort()
to get that.您可以使用 mongo 查询sort()
来获得它。 It can take value 1 or -1 according to sorting order, you can read mongo db document for more here .它可以根据排序顺序取值 1 或 -1,您可以 在此处阅读 mongo db 文档了解更多信息。
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. sort() 接受 Object 或字符串。
the correct syntax should be正确的语法应该是
const posts = await Post.find().sort({createdAt: 1});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.