How can I search between dates with nodejs and mongodb?

Asked

Viewed 420 times

-1

I would like to know how I can search between dates.

Example:

Bring all data between 06/12/2018 to 06/11/2019.

Bring all data for a given year or month.

How can I make these filters in my controller with nodejs and mongodb?

I tried it as follows but I did not succeed, it follows the index method of the Pedidocontroller class:

async index(req, res) {

const filters = {};

// filtro de pesquisa
if (req.query.data_min) {
  filters.createdAt.$gte = req.query.data_min;
}

const userLogado = await User.findById(req.userId);

// se não for um provedor
if (userLogado.provedor !== true) {
  const pedidos = await Pedido.find({
    cliente: req.userId
  }).populate("cliente");

  return res.json(pedidos);
}

const pedidos = await Pedido.paginate(filters, {
  page: req.params.id,
  limit: 10,
  populate: ["cliente"],
  sort: "-createdAt"
});

return res.json(pedidos);

}

  • has some error message?

  • No, it returns normal as if n had the filter..

  • Try to convert the value req.params.data_min for the guy Date

  • @Marcelovismari tried this but without success, I think it’s because my createdAt is saved in Datetime format (2019-12-24T16:42:11.669Z) in the database.

1 answer

0

I made the following change in my search condition and apparently this working as I would like. I used lib date-fns-timezone to format the date (it would not necessarily be necessary to format the date) I only used to leave by default the data_max with 23 hours, can put the same date in my data_min and data_max field and it will return all data from 00:00 hours to 23:00 hours. This was done because by default mongodb asks for a minimum date and a maximum date to be able to search between dates. Follow the change code.

if (req.query.data_min || req.query.data_max) {
  filters.createdAt = {};

  const dataMinFormatada = formatToTimeZone(
    req.query.data_min,
    "YYYY-MM-DDTHH:mm:ss.SSSZ",
    {
      timeZone: "America/Sao_Paulo"
    }
  );

  const dataMaxFormatada = formatToTimeZone(
    req.query.data_max,
    "YYYY-MM-DDT23:mm:ss.SSSZ",
    {
      timeZone: "America/Sao_Paulo"
    }
  );


  filters.createdAt.$gte = dataMinFormatada;
  filters.createdAt.$lte = dataMaxFormatada;
}

Browser other questions tagged

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