Mongodb query returns empty array

Asked

Viewed 120 times

-1

I have a route that receives a parameter in the format yyyy-mm(year-mes), I get this in the function below and do a search in my mongoDB database, but returns []:

const findYearMonth =  async (req, res) => {
  try {
    let data = [];
    const period = req.params.period;
    //console.log(`${typeof (period)} : ${period}`);
    data = await TransactionModel.find({yearMonth: period});
    JSON.stringify(data);
    if (!data) {
        res.status(500).send('Ocorreu um erro ao buscar valores');
    }
    else {
        res.send(data);
    }
  }catch (error) {
    res.send('Ocorreu um erro ao tentar encontrar as entradas:' + error);
  }
};

1 answer

0

Instead of using parameter, use query that looks better, what is wrong is that the parameter is probably not arriving at the query because it is a String and then what you can do to test is to make the query with a fixed value inside find (for example find({ yearMonth: "2020-01" }), remembering to change the route, so I passed should work:

const findYearMonth = async (req, res) => {
  try {
    let data = [];
    const period = req.query.yearmonth;
    //console.log(`${typeof (period)} : ${period}`);
    data = await TransactionModel.find({ yearMonth: period });
    JSON.stringify(data);
    if (!data) {
      res.status(500).send("Ocorreu um erro ao buscar valores");
    } else {
      res.send(data);
    }
  } catch (error) {
    res.send("Ocorreu um erro ao tentar encontrar as entradas:" + error);
  }
};

Change the route and in place of the parameter put this: ? yearmonth=2020-01

Or create a query in the tool you are using (Insomnia, Postman...)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.