hagopj13 / node-express-boilerplate

A boilerplate for building production-ready RESTful APIs using Node.js, Express, and Mongoose
MIT License
6.99k stars 2.05k forks source link

Filter by date #225

Open KingKnecht opened 2 years ago

KingKnecht commented 2 years ago

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

tuminzee commented 1 year ago

I am facing the same issue @KingKnecht did you find the solution to this?

KingKnecht commented 1 year ago

@tuminzee Sorry, for late response. To be honest I don't remember if I got it running or not. But when I check my code I find the following in my controller.js

const getPlannedDishs = catchAsync(async (req, res) => {
  const filterParams =  pick(req.query, ['from', 'to']);
  const dateRangeFilter = {
    "$gte" : filterParams.from,
    "$lte" : filterParams.to,
  }
  const mongooseFilter = {
    servedAt: dateRangeFilter
  }
  //const o = {servedAt: {"$gt":"2022-10-10T00:00:00Z"}}
  const options = pick(req.query, ['sortBy', 'limit', 'page', 'populate']);
  const result = await plannedDishService.queryPlannedDishs(mongooseFilter, options);

  res.send(result);
});

and in my service.js

 const queryPlannedDishs = async (filter, options) => {
  const plannedDishes = await PlannedDish.paginate(filter, options);

  console.log(JSON.stringify(plannedDishes));

  return plannedDishes;
};

So, for me it looks like I have provided extra parameters on the front-end, extracted my filter params and build a new one on the backend side.

tuminzee commented 1 year ago

Thank you for your response I will try it out @KingKnecht