Search code examples
mongodbsails.jssails-mongo

get records created within 24 hour in sails js


I want to fetch the Posts which are created within 24 hours in sails js. And I am using mongodb database. How do I get all those Posts which are created in past 24 hours.


Solution

  • You can create a date range that consists of 24 hours in the following manner.

    Using the momentjs library, you can create a date with the extension methods subtract() and cast it to a JS Date with the toDate() method:

    var start = moment().subtract(24, 'hours').toDate();
    

    or with plain vanilla Date objects, create the date range as:

    var now = new Date(),
        start = new Date(now.getTime() - (24 * 60 * 60 * 1000));
    

    Use the where() method to use the query the Posts model using the above date range query, given the field which holds the timestamp is called date:

    Posts.find()
        .where({ "date" : { ">": start } })
        .exec(function (err, posts) {
            if (err) throw err;
            return res.json(posts);
        });