Search code examples
sails.jswaterlinesails-mongo

Sails JS - Waterline ORM - Query Date only, not Time


Looking to query against the date only anyone encountered this?

Sample code:

    ////MODEL
    module.exports = {
      attributes: {
        date: {
            type: 'date',
            required: true
        }    
      }
    };

    ////CONTROLLER
    var today = moment().toISOString();

    var queryObj = { date: today };
    var newDay = { date: today };

    Day.findOrCreate(queryObj, newDay).exec(function(err, day) {            
        console.log(day)
    });

Obviously this creates a new record on each refresh, as the iso string will change with each passing second.

Thanks for the help!


Solution

  • Instead of querying for a single date, you can query for a date range that includes all of today. First, you'll need to actually create values for that range--I whipped this up using Moment, but there's probably a better way:

    var begin = moment(moment().format("YYYY-MM-DD")).toISOString();
    var end = moment(moment().format("YYYY-MM-DD")).add(1, 'days').toISOString();
    

    Then you can use query operators to search the range:

    var queryObj = {date: {'>=': begin, '<': end}};
    Day.findOrCreate(queryObj, newDay).exec(function(err, day) {            
        console.log(day)
    });
    

    As always, be mindful of time zone issues!