Posted in General

Mongoose and momentjs

A seemingly simple issue came up with a side project of mine. Date queries can be quite a nuisance when passing this information from a datepicker in a view, to an Angular controller, through an express route and finally to some query that grabs the data and returns it back in a promise.

There are several stackoverflow posts like this one that hint at formatting your date prior to querying for the data on the backend. In my case, I used Mongoose.

Here is what I ended up doing when I wanted to specify a “date string” in the format “MM/DD/YYYY” to the backend. The express API looked something like this:

http://someserver.com/api/billinglogs/user/55ab9e79f794762b4f2cd36f/serviceDt/02%2F20%2F2016

Where this is a query to retrieve all billing records for a particular user on a specific day.

The Mongoose call within the express middleware went something like this:

exports.getBillingLogsByUserAndDate = function(req, res) {
   var startOfDay = moment(req.params.serviceDate, 'MM/DD/YYYY')
                          .startOf('day').format('MM/DD/YYYY'),
   nextDay = moment(startOfDay, 'MM/DD/YYYY').add(1,'days')
                   .format('MM/DD/YYYY');

   console.log('startOfDay: ' + startOfDay);
   console.log('nextDay: ' + nextDay);
   BillingLog.find({
      _userId: new ObjectId(req.params.id),
      serviceDate: {
         $gte: startOfDay,
         $lt: nextDay
      }
   }).exec(function(err, billingLogs) {
      res.send(billingLogs);
   })
};

ObjectId is just the value passed into req.params.id:

55ab9e79f794762b4f2cd36f

 

The console.log statements will output something like the following:

startOfDay: 02/20/2016
 nextDay: 02/21/2016

 

 

 

 

Author:

I love to learn. I am not so interested in buzzwords when it comes to gadgets. I would rather see how they work. Software is no different. Just trying to be better one byte at a time ^_^