【问题标题】:How to search mongodb createdAt date using string如何使用字符串搜索 mongodb createdAt 日期
【发布时间】:2022-01-04 05:34:15
【问题描述】:

我正在创建一个搜索栏,使用 react 在 mongodb 文档中查找多个数据字段。我将一个关键字从前端发送到 NodeJS api 以搜索包含该关键字的文档。到目前为止,我可以搜索任何字符串值字段。但我想搜索 createdAt 日期值也使用相同的搜索。

例如,我想使用“2021-26-11”这个字符串值来获取所有已创建的文档。以下是我的猫鼬状况

 var condition = title ? { $or: [{ title: { $regex: new RegExp(title), $options: "i" } }, { author: { $regex: new RegExp(title), $options: "i" } },{ createdAt: { $regex: new RegExp(title), $options: "i" } }] } : {};

【问题讨论】:

    标签: javascript node.js reactjs mongodb mongoose


    【解决方案1】:

    var condition = title ? { $or: [{ title: { $regex: new RegExp(title), $options: "i" } }, { author: { $regex: new RegExp(title), $options: "i" } },{ createdAt: new Date(title) }] } : {};

    你可以试试这个方法,但一定要检查

    • 您的title 日期格式是否有效。
    • 如果是日期,请确保添加 Greather then that Date and Less than the end of the date - 条件。

    【讨论】:

      【解决方案2】:

      或者您可以获取创建日期的timestamp,然后在搜索中放置一个日期选择器并使用该时间戳进行比较,不会处理正则表达式

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-06
        • 2016-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-06
        相关资源
        最近更新 更多