Home > Blockchain >  Search mongodb data using the lt & gt comparators on the date
Search mongodb data using the lt & gt comparators on the date

Time:10-25

const queryMatch = {departureDate: {$gte: new Date(query.departureDateMin),$lte: new Date(query.departureDateMax)}};
const flightsByCriteria = await this.flightModel.find(queryMatch).exec();

The above request returns an empty table. And yet I get data with mongodbCompass using ISODate(dateString) instead of new Date(dateString)

I don't know where the problem lies in my request ? Thank for your help.

CodePudding user response:

You should send the dates from the client side in ISO format, so the server would not covert them to the server local time.

When you are sending dates from the client, you can just send them with calling .toISOString() method:

{
  departureDateMin: new Date(departureDateMin).toISOString(),
  departureDateMax: new Date(departureDateMax).toISOString(),
}

Then, you can query database like this:

const queryMatch = {
  departureDate: {
    $gte: query.departureDateMin,
    $lte: query.departureDateMax,
  }
};

CodePudding user response:

model.find({
  departureDate: {
    $gte: new Date(query.departureDateMin),
    $lte: new Date(query.departureDateMax),
  },
});
  • Related