Arthur
Arthur

Reputation: 5158

Mongo Observe when a document date field is past

I'm using MongoDB with MeteorJS, and I want to know if it's possible to observe a field value ? I know we can observe a doc update, creation, or removing but I don't know about field value.

Each of my document have a field named time_next_action (with a Javascript Date value) and I want update each document when this attribute is past.

Actually I have a interval called 2 times/second, but :

This is my actual code (but I don't like that)

Meteor.setInterval(function() {
 beginIntervals();
}, 500);

let beginIntervals = function() {
  let now = new Date()
  let games = Games.find({time_next_action: {'$lt': now}}).fetch()

  _.each(games, game => {
    /* Do something */
    Games.update(game._id, {'$set': update})
  })
}

Upvotes: 1

Views: 104

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20256

Use the remcoder:chronos package to define a reactive time variable then wrap your update in a Tracker.autorun:

let now = Chronos.currentTime();

Tracker.autorun(function(){
  let games = Games.find({ time_next_action: { $lt: now }}).fetch();
  _.each(games, game => {
  /* Do something */
    Games.update(game._id, {'$set': update})
  })
});

However the effect is basically the same as your code, just a bit more concise. Chronos will update the reactive time every second (changeable) and that will cause the tracker to fire which will run a find and then do your updates.

Upvotes: 1

Related Questions