Search code examples
javascriptnode.jsmongodbexpressmongoose

Mongo find() query with regexp not filtering


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
        }
    });

Hello I'm trying to use regexp to filter out data with a specific month. It finds the data without the regexp but once I put it in it returns an empty array.


Solution

  • I think the problem may be that you are not escaping the backslashes

    const regexp = new RegExp("\\d\\d\\d\\d-" + month + "-\\d\\d");