Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 858
pim Avatar asked Aug 18 '15 17:08

pim


1 Answers

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!

like image 54
sgress454 Avatar answered Dec 06 '22 20:12

sgress454