0

I have data in the ISOdate format in MongoDB. When I run the query in mango shell it works correctly.

But the same query when I used in nodejs it gives an error

USED IN NODEJS
       router.get("/api/status/:id0/:id1",async(req,res)=>{
                ..........
                ..........   
            db.collection.aggregate([
                        {$match:
                          {"time": {
                            "$gt": req.params.id0,//req.params.id0.toISOString()
                            "$lt": req.params.id1}
                          }
                        },
                        {$group:
                           { 
                             _id: "$fb_id",
                             active:"$status"
                           }
                        }
                      ]);
 URL

  localhost:3011/status/"2019-12-15T09:19:57.216071"/"2019-12-16T09:25:03.508605"
  or 
  localhost:3011/status/2019-12-15T09:19:57.216071/2019-12-16T09:25:03.508605
  0r
  localhost:3011/status/%222019-12-15T09%3A19%3A57.216071%22%2F%222019-12-16T09%3A25%3A03.508605%22%0D%0A

Still not fetch value

harry
  • 31
  • 4

2 Answers2

0

Nodejs (express) parses all route and query params as a string. In your case the 2 params are in ISODate format, but they are still strings. In order for your aggregate query to work you need to pass them as Date/ISODate objects.

db.collection.aggregate([
  {
    $match: {
      "time": {
        "$gt": new Date(req.params.id0),
        "$lt": new Date(req.params.id1)
      }
    }
  },
...
])

You can checkout this example as well.

Ivaylo Atanasov
  • 215
  • 1
  • 6
-1

From your example ISO Date string is not a valid.

Eg: In the given date time zone is missing "Z" "2019-12-15T09:19:57.216071"

InCorrect ISO Date Format

new Date("2019-12-15T09:19:57.216071")

Sun Dec 15 2019 09:19:57 GMT+0530 (India Standard Time)

Valid/ Correct ISO Date Format

new Date("2019-12-15T09:19:57.216071Z")

Sun Dec 15 2019 14:49:57 GMT+0530 (India Standard Time)

Mohan Ohanra
  • 101
  • 3