【问题标题】:How do I sort by time(string) for Mongoose?如何按时间(字符串)为 Mongoose 排序?
【发布时间】:2021-11-06 14:20:31
【问题描述】:

我正在尝试根据字段'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

关于如何排序有什么建议吗?

【问题讨论】:

    标签: string mongodb date mongoose


    【解决方案1】:

    据我所知,猫鼬中没有内置的排序修饰符可以满足您的要求。

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

    这是一个参考帖子:How to define a sort function in Mongoose

    【讨论】:

      【解决方案2】:
      const users = await UserModel.find({}).sort({'time': 'desc'}).exec();
       
      

      从 v3.8.1 开始:

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

      【讨论】:

        猜你喜欢
        • 2015-10-29
        • 1970-01-01
        • 2019-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-08
        相关资源
        最近更新 更多