【问题标题】:How to sort the documents based on date strings in mongoose如何根据猫鼬中的日期字符串对文档进行排序
【发布时间】:2019-07-23 08:00:27
【问题描述】:

我正在尝试使用猫鼬根据日期值对我的收藏进行排序。当我使用排序功能时,它无法按预期工作。

以下是我使用的查询。

const filters = {};
filters.spacecategory = { $in: spaceId };
const sortingQuery = { publishedDate: -1 };
const filteredFeeds = await Feed.find(filters).sort(sortingQuery);

publishedDate 具有以下格式 MongoDB中的日期格式为“Fri Mar 29, 2019 21:21:25 GMT+0530(印度标准时间)”

非常感谢您的帮助,谢谢。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    为此,您需要使用聚合管道。在排序之前,在项目1 中使用 [$dateFromString] 将字符串转换为日期。

    喜欢:

    db.collectionname.aggregate([
        {
           $project: {
              date: {
                 $dateFromString: {
                    dateString: '$date',
                    timezone: 'America/New_York'
                 }
              }
           }
        },
        {
            $sort : {"date" : 1}
        }
    
        ])
    

    【讨论】:

    • 我试过这个选项。但是我遇到了一个错误。以下是我的代码。 const filtersFeeds = await Feed.aggregate([ { $match: filters }, { $project: { publishedDate: { $dateFromString: { dateString: '$publishedDate', // timezone: 'America/New_York', }, }, } , }, { $sort: { publishedDate: 1 }, }, ]);
    • Unhandled Rejection at: Promise Promise { RangeError: Invalid status code: undefined 我得到这个错误。 publishedDate 是我的模型中所拥有的
    • 您缺少日期格式。请查看 $datefromstring 函数的文档
    • 我可以转换这种格式吗:Fri Mar 29, 2019 21:21:25 GMT+0530(印度标准时间)?因为这是我试图转换和排序的内容
    猜你喜欢
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2020-08-10
    • 2020-03-26
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多