Filter by date
Author: KingKnechtCreated Oct 16, 2022Updated Jun 3, 2025
I'm trying to filter a date with $gt. This is what I give my axios method on client side for an exact date (which works):
params: {
sortBy: 'name:asc',
limit: 200,
page: 1,
servedAt: `${format((new Date()),"yyyy-MM-dd'T'HH:mm:ss'Z'")}`,
},But if I try to put more logic in it, it fails:
params: {
sortBy: 'name:asc',
limit: 200,
page: 1,
servedAt: `{$gt: ${format((new Date()),"yyyy-MM-dd'T'HH:mm:ss'Z'")} }` // <=== Invalid cast
},server side looks like:
const getPlannedDishs = catchAsync(async (req, res) => {
const filter = pick(req.query, ['servedAt']);
const options = pick(req.query, ['sortBy', 'limit', 'page']);
const result = await dishService.queryPlannedDishs(filter, options);
res.send(result);
});
Error message is:
message: Cast to date failed for value "{$gt: 2022-10-13T00:00:00Z }" (type string) at path "servedAt" for model "PlannedDish"
at model.Query.exec (C:\Users\KingKnecht\source\repos\Mampf-KO\backend\node_modules\mongoose\lib\query.js:4498:21)
at Function.schema.statics.paginate (C:\Users\KingKnecht\source\repos\Mampf-KO\backend\src\models\plugins\paginate.plugin.js:39:54)How could I achieve the filtering? Thx
Source: hagopj13/node-express-boilerplate