Search code examples
javascriptmongodbmeteormeteor-react

Modify Meteor-React ToDo List Example to Display List Items Created Within a Time Range


I'm working through the Meteor-React Todo list tutorial as found here https://www.meteor.com/tutorials/react/creating-an-app

As per 8.4, we can add a button that hides todo items that are checked off. We do this by querying the DB for items that checked equals true.

if (this.state.hideCompleted) {
        // If hide completed is checked, filter tasks
        query = {checked: {$ne: true}};
    }

If I wanted to only display todo items that were created in the last 30 minutes, ie todo items expire after 30 minutes, what would I set the query to?

My guess is something like this

if (this.state.hideExpired) {
        // If hideExpired state true, only display todo items created in the last 30 minutes.
        query = {{$ne: (currentTime - createdAt) < 30 minutes}};
    }

Solution

  • Pretty close but you need to use $lte or $gte instead of $eq:

    if (this.state.hideExpired) {
      var now = new Date();
      var thirtyMinutesAgo = new Date() - 30 * 60 * 1000; //
      query = { createdAt: { $gte: thirtyMinutesAgo }}
    }
    

    Note that this query will not be reactive. This is because thirtyMinutesAgo is not a reactive variable. If you want items to dynamically disappear from the list as they age you'll need to make time itself reactive. For this I recommend the remcoder:chronos package. With that package installed the above code would become:

    if (this.state.hideExpired) {
      var now = new Date();
      var thirtyMinutesAgo = Chronos.currentTime() - 30 * 60 * 1000; //
      query = { createdAt: { $gte: thirtyMinutesAgo }}
    }
    

    Chronos.currentTime() will update every second by default and thirtyMinutesAgo will be a reactive variable.