1
Meteor.publish('mountCarmelData', function dataPublication(){
    return MountCarmel.find({}, 
    {
        sort: {created_at: -1}
    });
});

Is there any way to limit this publication to publish only the past 24 hour of data? I have a timestamp on each record called 'created_at'.

  • 2
    Possible duplicate of [return query based on date](http://stackoverflow.com/questions/8835757/return-query-based-on-date) – chazsolo Feb 13 '17 at 19:19

2 Answers2

3

You can use moment.js to get a timestamp that is exactly 24 hours less than the current date:

let yesterday = moment().subtract(24, 'hours').toDate();

Then in your publication:

Meteor.publish('mountCarmelData', function dataPublication(){
    return MountCarmel.find(
    {
        createdAt: { $gte : yesterday }
    }, 
    {});
});

I have removed the 'sort' because sorting on the server won't cause your documents to be sorted in MiniMongo. You'll need to add the 'sort' in your Blaze helper or React Container for it to work.

Sean
  • 2,609
  • 1
  • 18
  • 34
  • 4
    `yesterday` in your code is a moment object, not a date or timestamp. You should probably convert it before checking against it. – chazsolo Feb 13 '17 at 21:17
0

You can create a query to do what you want, but the problem is in the way that subscriptions will pull data to the client without removing the old data. You can address this by filtering the data on the client so that it only shows 24 hours worth of data, but if the app is left running the collection will grow large, and possibly take up too much memory in the browser.

I would recommend that you have a separate collection for just 24 hours of data. This makes it a lot simpler to deal with on the client side, as you simply subscribe to the data.

Have a look at this question and answer for a similar scenario: Publish only things who were read 10seconds ago from now

@jerome was successful with this technique

Community
  • 1
  • 1
Mikkel
  • 7,693
  • 3
  • 17
  • 31