0

I am creating a rest API for my company for reporting Routs to pass dates to find data from 2 given dates

router.get('/smDcr/:currentDate?&:lastDate:', authorize, getDcrBetweenDates);

Controller action to get the data between dates

exports.getDcrBetweenDates = async(req, res, next) => {
    try{
        const lastDate = req.params.lastDate;
        const currentDate = req.params.currentDate;
        console.log(lastDate);
        const dcr = await Dcr.find({
            where: {
                createdAt: {
                    $between:[currentDate, lastDate]
                }
            }
        });
        if(!dcr) return res.status(400).json({message: "No DCR found between mentioned Dates!!"});
        return res.status(200).json({ dcr});

    }catch(ex){
        next(ex)
    }

}

while passing parameter in postman I am getting all reports not specific to the dates given in params http://localhost:3000/smDcr/?currentDate=2019/09/11&?lastDate=2019/09/11

2 Answers2

1
  1. You don't need to use $where condition, you just can set your request object inside find function

  2. I think you should use $gte and $lte operators, instead of $between (cf @ponzao answer)

Here is an example :

const dcr = await Dcr.find({
    "createdAt": {
        "$gte": new Date(currentDate),
        "$lt": new Date(lastDate)
    }
});

EDIT:

If it still doesn't works, it is probably because your dates are not formatted, maybe you should use a date library, like moment, and try like this :

const moment = require('moment');
const dcr = await Dcr.find({
    "createdAt": {
        "$gte": new Date(moment(currentDate, 'YYYY/MM/DD').format()),
        "$lt": new Date(moment(lastDate, 'YYYY/MM/DD').format())
    }
});

Hope it helps.

Sparw
  • 2,688
  • 1
  • 15
  • 34
0

It will be better if you use query strings instead of query params for atleast dates. In the route you provided that is :

router.get('/smDcr/:currentDate?&:lastDate:', authorize, getDcrBetweenDates);

using ?&: in url to pass 2nd date value will get interpreted as querystring because of (?). And you are accessing this end point by calling this :

http://localhost:3000/smDcr/?currentDate=2019/09/11&?lastDate=2019/09/11

In this, currentDate will be considered as query string and same is the case with lastDate

So I would suggest you to use this instead :

router.get('/smDcr', authorize, getDcrBetweenDates);

And in your controller, access the values like this :

    const lastDate = req.query.lastDate;
    const currentDate = req.query.currentDate;

And to access it you should be calling :

http://localhost:3000/smDcr?currentDate=2019/09/11&lastDate=2019/09/11

Here is a official doc for routing. Express Routing

Mudit Juneja
  • 165
  • 9