Back

Technologies:

javascriptjavascript
node.jsnode.js
avatar
Tolerim
25 days ago

How can I make a MongoDB find() query using regexp that filters correctly?

Here is the modified paragraph: Hello, I am attempting to filter data records based on a specific month using regular expressions (regexp). Although the code works when not using regexp, the application is returning an empty array when I include it. Below is the modified code:

app.get("/expenses/:month", async (req, res) => {
    const { month } = req.params;
    const regexp = new RegExp("\d\d\d\d-" + month + "-\d\d");
    console.log(regexp);
    const allExpenses = await Expense.find({ date: { $regex: regexp } });
    const allEarnings = await Earning.find({ date: { $regex: regexp } });
    console.log(allExpenses);
    res.status(200).json({
        status: "success",
        results: allExpenses.length,
        data: {
            allExpenses,
            allEarnings
        }
    });
Please let me know if you have any questions or concerns.
Answers(2)
avatar
Vogi
24 days ago
Verified Answer
Thank you for sharing your code with me. It looks like you are trying to filter data records based on a specific month using regular expressions. I noticed that you are using the following line of code to create a regular expression:
const regexp = new RegExp("\d\d\d\d-" + month + "-\d\d");
The problem with this line of code is that the backslashes are not being escaped properly. You should use double backslashes instead of single backslashes to escape the digits in the regular expression. Here is the corrected line of code:
const regexp = new RegExp("\\d\\d\\d\\d-" + month + "-\\d\\d");
This should fix the issue you are experiencing with your application returning an empty array when you include the regular expression. I hope this helps! Let me know if you have any other questions or concerns.

Sources

Filter by date - Excel formula | ExceljetAll the Ways to Filter Pandas Dataframes • datagypython - How to filter rows in pandas by regex - Stack OverflowHow to filter data based on the month and year value
avatar
Tolerim
25 days ago
It looks like the issue might be with how you're creating the RegExp object. When creating a RegExp object using a string, backslashes need to be escaped with another backslash. So, instead of const regexp = new RegExp("\d\d\d\d-" + month + "-\d\d");, try using const regexp = new RegExp("\\d\\d\\d\\d-" + month + "-\\d\\d");. This should correctly create a regular expression that matches dates in the format of "yyyy-mm-dd" with the given month. Give that a try and see if it helps resolve the issue.
;