Home > Net >  How to pass Query Params in mongo db aggregation pipeline using node js
How to pass Query Params in mongo db aggregation pipeline using node js

Time:08-04

I have a GET API which fetches pipeline from mongo collection which consists of request query parameters which needs to get assigned and evaluated in the aggregation pipeline.

My Aggregation Pipeline:

db.collection.aggregate(
  {
    "$match": {
      "TaskCompletedDate": { "$gte": "new Date(`${req.query.startDate}`)", "$lt":"new Date(`${req.query.endDate}`)" }
    }
  },
  {
    "$group": {
      "_id":{
        "ProductTypeCode":"$ProductTypeCode"
      },
      "count": { "$sum": 1 }
    }
  },
  {
    "$project": {
      "_id":0,
      "concat":{ "$concat": [{ "$toString": "$count" }, "$_id.ProductTypeCode"] }
    }
  }
]).toArray();

My Request:

http://localhost:3000/procedure/?startDate=2022-01-12T00:00:00:0Z&endDate=2022-01-23T00:00:00:0Z

But In response I am able to see empty array. When I remove this dates related match condition and try to run this pipeline I am able to see response. But these dates which I pass through query params should assign it into pipeline needs to get executed and need to display the desired result which I am not getting it. Can anyone please help me on this

CodePudding user response:

So as mentioned in the comments the issue you have is to your not actually passing the date and using it properly.

The way it should be:

{
    "$match": {
        "TaskCompletedDate": {
            "$gte": new Date(req.query.startDate),
            "$lt": new Date(req.query.endDate),
        }
    }
}

The JSON error you mention is actually an invalid time parsing that causes this error, the input string:

2022-01-12T00:00:00:0Z

Is not a valid date, this is it's valid version: (YYYY-MM-DDTHH:mm:ss.sssZ), you can read about the format here

2022-01-12T00:00:00.0Z

( the last : is now a . ).

  • Related