0

I don't know why it's not working while trying to do a match inside array of strings which comes from client's request query. This is what I've tried to do filter from my database

const serviceTypes = ["Hybrid", "Special", "Normal"];

if (req.query.serviceTypes) {
   serviceTypes = req.query.serviceTypes;
}
....

const packagesList = await PackagesList.aggregate([
....
// here I did an aggregation which works all fine if there is no req.query.serviceTypes
....

      {
        $match: {
          isActive: true,
          "packageService.serviceType": {
            $in: serviceTypes,  // I've also tried to directly feed `JSON.parse(req.query.serviceTypes)`
          },
        },
      },

What confuses me is it works well if I didn't send any request query in the header and I tried to see what it gets in my console and the output is all fine. i.e if I send this in the request serviceTypes=['Hybrid', 'Normal']

my console.log(JSON.parse(req.query.serviceTypes)); output looks like

['Hybrid', 'Normal']

But the result is an empty array even though there exist a valid data in my database.

Kirubel
  • 1,461
  • 1
  • 14
  • 33
  • And another funny thing, this method works with `POST` method – Kirubel Nov 16 '20 at 12:58
  • 1
    Try deconstruction: [...req.query.serviceTypes] Or Loadash: _.map(req.query.serviceTypes, _.clone); – xIsra Nov 16 '20 at 13:08
  • @IsraelKouperman but what makes the difference if I still can do this in `req.body.serviceTypes` – Kirubel Nov 16 '20 at 13:54
  • Change `const` to `let` - https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var – xIsra Nov 17 '20 at 08:50
  • Are you not getting any `TypeError: Assignment to constant variable` when `if` statement is true? – vishnu Nov 17 '20 at 09:14
  • No. There is no error at all but rather it responds with an Empty array – Kirubel Nov 17 '20 at 12:19
  • @Kirubel Can you try adding a `console.log` just after the `if` statement and make sure that the code below it is executing in both cases (When you pass query string and when not passing) – vishnu Nov 18 '20 at 01:56
  • @Vishnu yes I've tried to see inside the `if` statement before it goes there and also after. In all scenarios I'm able to get the query parameter array value but the `$match` result is empty. – Kirubel Nov 18 '20 at 07:35
  • Please add the full code of your request. – xIsra Nov 25 '20 at 10:49

0 Answers0