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:

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')
   nextDay = moment(startOfDay, 'MM/DD/YYYY').add(1,'days')

   console.log('startOfDay: ' + startOfDay);
   console.log('nextDay: ' + nextDay);
      _userId: new ObjectId(,
      serviceDate: {
         $gte: startOfDay,
         $lt: nextDay
   }).exec(function(err, billingLogs) {

ObjectId is just the value passed into



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

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






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 ^_^