MongoDB/Mongoose – Find all where a specific Date is in a Date Range

Tags: , , , ,



for example I have documents with this field:

startDate: 2021-04-14T22:00:00.000+00:00
endDate: 2021-04-19T22:00:00.000+00:00

and I want to get all documents where a specific date (like today) is in the date range. Is it possible to make such a query? For example if I search for 18th April, then I get that document.

I thought something like this:

db.posts.find(
{
 $gte: { startDate: new Date() },
 $lt: { endDate: new Date() }
});

But this doesn’t work… I get an error The provided parameters were invalid. Check your query and try again.

I think new Date() is not correct in Node.js?

EDIT:

This is my Controller:

const getActiveTours = async (req, res) => {
  try {
    const activeTours = await Tour.find({
      startDate: { $gte: new Date() },
      endDate: { $lt: new Date() },
    }).exec();
    res.status(200).send(activeTours);
  } catch (error) {
    return res.status(500).send({ errorMessage: error });
  }
};

I exported it and here is my endpoint:

router.get('/getactivetours', tourController.getActiveTours);

I tried to call this in Postman but get an empty [] back…

Answer

Your syntax is wrong, try this one:

db.posts.find(
{
 startDate: {$gte : new Date() },
 endDate: {$lt : new Date() }
});


Source: stackoverflow