bartezr
bartezr

Reputation: 789

Meteor & MongoDB. Troubles with getting data from collection (finding documents between two dates)

I'm trying to get some documents from collection located between two dates(with 5 hour difference for example). My code:

Session.setDefault('sortBy', 'time');
    Template.content.helpers({
        posts: function() {
            if( Session.equals('sortBy', 'time') ){
                return Posts.find({author: Meteor.user().username}, {sort: {date_created: -1}});
            } 
            else if( Session.equals('sortBy', 'hours') ) {
                var endDate = new Date();
                var startDate = new Date(endDate);
                startDate.setHours(endDate.getHours()-5);
                console.log("startDate: " + startDate);
                console.log("endDate: " + endDate);

                return Posts.find({author: Meteor.user().username}, {date_created: {$gte: startDate,$lt: endDate}})
            }
        }
    });
    Template.content.events({
        'click .lasthour': function(e) {
            return Session.set('sortBy', 'hours');
        },
        'click .nosort': function(e) {
            return Session.set('sortBy', 'nosort');
        }
    });

But it always returns all documents (so filter not working). And problem not in Session variable 'sortBy', it working fine.

Upvotes: 0

Views: 140

Answers (1)

Jordan Speizer
Jordan Speizer

Reputation: 573

Your query is formatted wrong. Should look like this:

return Posts.find(
  {
    author: Meteor.user().username,
    date_created: {$gte: startDate, $lt: endDate}
  }
);

Upvotes: 1

Related Questions