Emibrown
Emibrown

Reputation: 187

how to check my mongodb for expired post and change their status to expired using nodejs

I want to create a service that runs through my mongodb to check for expired post and automatically update their status to "expired" here is what i did

setInterval(function(){
  Post.find({}, function(err, posts) {
  if (err) { 
    return
   }else{
    for (var i = posts.length - 1; i >= 0; i--) {
      var current = moment();
      if( moment(current).isSameOrAfter(posts[i].expiredOn)){
          Post.update({ _id: posts[i]._id},{status:"expired"}, function(err){
              if (err) { 
                return; 
             }
          })
        }
      }
    }
  });
 }, 5000);

thhis function runs every 5 seconds on my nodejs server Please is this the right way of it? if no, how can i fix it?

Upvotes: 0

Views: 106

Answers (1)

Matthew Antolovich
Matthew Antolovich

Reputation: 508

Instead of doing a find every time, in which the result set can be very large, you can just issue an update without finding all posts first, looping over them, and updating only the ones that match the criteria. This will result in less database calls, and quicker execution.

setInterval(function() {
    Post.update({
        expiredOn: {
            $gte: new Date()
        }
    }, {
        $set: {
            status: "expired"
        }
    }, {
        multi: true
    }, function(err) {
        if (err) {
            return;
        }
    });
}, 5000);

Upvotes: 1

Related Questions