Issue with querying dates with $gte and $lt

0

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

type or paste code here

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

This is how data looks like in MongoDB Compass:
“manufacturingDate”: “2020-10-14T07:00:00.000Z”,

And error in my VS Code compiler

I do not know mongoose very because I stir away from such obstruction abstraction layer.

You name your model Containers with

so I think you need to use Containers rather than Container in

I don’t think this has to do anything with my error. My code works fine if I write date by hand and not use $gte: startDate,

Can you add the lines

const gte_Date = new Date( startDate ) ;
const lt_Date = new Date( endDate ) ;

just before

and replace

with

$gte : gte_Date ,
$lt : lt_Date ,

If that still fails, I suspect you need to import or require so that you refer to same Date type as the one used by mongoose schema.

By the way your $or is useless since you have a single object/condition inside its array.