Reputation: 3015
I currently have a template where I am querying the database with the following query.
allMessages = Messages.find({$or: [{type: "user_message"}, {type: "system_message", time: {$gt: (Date.now() - 180000)} }]}, {sort: {time: 1 }}).fetch()
Now obviously the template helper gets re-run whenever something new goes into or is removed from this set of data, which is exactly what I want. The issue arises when a system_message
gets older than 2 minutes and I no longer want that message to by apart of my query. The data does not update when this happens, and only updates when a new message comes in or a for some reason a message is removed.
Does anyone know why this might be the case? It seems to me that there shouldn't be an issue as the data on the query is changing so it should be re-running but it isn't.
Upvotes: 0
Views: 46
Reputation: 64312
It isn't working because Date.now()
isn't a reactive variable. If you were to set the date limit in something like a session variable or a ReactiveDict, it would cause your helper to recompute. Here's an example using the Session
:
Template.myTemplate.allMessages = function() {
var oldestMessageDate = Session.get('oldestMessageDate');
var selector = {
$or: [
{type: "user_message"},
{type: "system_message", time: {$gt: oldestMessageDate}}
]
};
return Messages.find(selector, {sort: {time: 1}});
};
Template.myTemplate.created = function() {
this.intervalId = Meteor.setInterval(function() {
Session.set('oldestMessageDate', new Date - 120000);
}, 1000);
};
Template.myTemplate.destroyed = function() {
Meteor.clearInterval(this.intervalId);
};
Every second after the template is created, it changes oldestMessageDate
to a new date which is two minutes in the past. Note that the intervalId
is stored in the template instance and later cleaned up in the destroyed
callback so it won't keep running after the template is no longer in use. Because oldestMessageDate
is a reactive variable, it should cause your allMessages
helper to continually rerun.
Upvotes: 2