Sails JS - Waterline ORM - Query Date only, not Time
Asked Answered
H

1

5

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!

Hudibrastic answered 18/8, 2015 at 17:7 Comment(1)
Just a comment that type:'date' is being deprecated in Sails v1.x. I think the advised method is to type:'string', columnType:'date' (or timestamp)Oppose
C
9

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!

Confounded answered 18/8, 2015 at 18:8 Comment(1)
DUHH how did I miss that! #linearthinking -- thanks friend.Hudibrastic

© 2022 - 2024 — McMap. All rights reserved.