Home > Enterprise >  Issue with querying dates with $gte and $lt
Issue with querying dates with $gte and $lt

Time:06-08

I want to make searchDate API (I am using Express, Mongoose and Angular). I need to return list of data between two dates.

Somehow it is working only if I hardcode date in $gte and $lt

My api code:

    router.get("/searchDate", async (req, res) => {
  try {
    const { startDate, endDate } = req.query;

    const containers = await Container.aggregate([
      {
        $match: {
          $or: [
            {
              manufacturingDate: {
                $gte: new Date(startDate),
                $lt: new Date(endDate),
              },
            },
          ],
        },
      },
    ]);
    res.status(200).json(containers);
  } catch (err) {
    res.status(404).json({ success: false, msg: "Container not found" });
  }
});

And my model is:

import * as mongoose from "mongoose";
const ContainerType = require("./ContainerType");

const Schema = mongoose.Schema;

const ContainerSchema = new mongoose.Schema({
  owner: { type: String, required: true },
  manufacturingNo: { type: String, required: true },
  IdentificationNo: { type: String, required: true },
  manufacturingDate: { type: Date, required: true },
  nextInspectionDate: { type: Date, required: true },
});

module.exports = mongoose.model("Containers", ContainerSchema);

That is how the date looks in my MongoDB Compass enter image description here

An error I am getting from the api /searchDate is: enter image description here

CodePudding user response:

This actually has nothing to do with Mongo, and is just a regular TypeScript error.

The startDate and endDate variables are not (as far as TS can tell) necessarily safe to construct a Date object from.

You can either cast, e.x. new Date(String(startDate)), or better, assert or throw somewhere above if typeof startDate !== 'string'.

This is assuming that startDate is indeed a string, which is highly likely but not necessarily true (as TypeScript is telling you).

Keep in mind it's also possible that constructing a Date from a string can result in an Invalid Date object.

  • Related