如何按Mongoose的时间(字符串)排序?



我正试图根据字段'time'

对一些文档进行排序这是我目前排序文档的方式:

const users = await UserModel.find({}).sort('time');

现在数据看起来是这样的:(CSV格式)

time,name
10:30 AM,John Smith
12:30 PM,Elsa Smith
2:30 PM,Jo Smith
8:30 AM,Gale Smith

然而,它是根据第一个数字而不是时间排序的。不幸的是,我无法将数据库中的数据类型更改为当前字符串以外的任何其他类型。

需要根据时间正确排序,如下所示:

time,name
8:30 AM,Gale Smith
10:30 AM,John Smith
12:30 PM,Elsa Smith
2:30 PM,Jo Smith

有什么建议吗?

const users = await UserModel.find({}).sort({'time': 'desc'}).exec();

From v3.8.1:

const users = await UserModel.find({}).sort('time', -1).execFind();

据我所知,在mongoose中没有内置的排序修饰符可以实现您的请求。

一个好的解决方法是根据找到的结果实现自己的排序函数。

这是一篇参考文章:如何在Mongoose中定义排序函数

最新更新