for example I have documents with this field:
JavaScript
x
3
1
startDate: 2021-04-14T22:00:00.000+00:00
2
endDate: 2021-04-19T22:00:00.000+00:00
3
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:
JavaScript
1
6
1
db.posts.find(
2
{
3
$gte: { startDate: new Date() },
4
$lt: { endDate: new Date() }
5
});
6
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:
JavaScript
1
12
12
1
const getActiveTours = async (req, res) => {
2
try {
3
const activeTours = await Tour.find({
4
startDate: { $gte: new Date() },
5
endDate: { $lt: new Date() },
6
}).exec();
7
res.status(200).send(activeTours);
8
} catch (error) {
9
return res.status(500).send({ errorMessage: error });
10
}
11
};
12
I exported it and here is my endpoint:
JavaScript
1
2
1
router.get('/getactivetours', tourController.getActiveTours);
2
I tried to call this in Postman but get an empty [] back…
Advertisement
Answer
Your syntax is wrong, try this one:
JavaScript
1
6
1
db.posts.find(
2
{
3
startDate: {$gte : new Date() },
4
endDate: {$lt : new Date() }
5
});
6