Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cursor.observe({added}) behavior in Meteor

Tags:

meteor

I'm trying to display an alert to the user when data is added to the database. So I wrote (on the client side) :

Meteor.autosubscribe(function() {
  ItemCollection.find().observe({
    added: function(item) {
      // Alert code
    }
  });
});

And I found that not only alerts are displayed when a new item is added to the database on the server side ( which I suppose is normal :) ) but alerts are also displayed for each previously added item when I refresh the page. I suppose Meteor fetch all the data from the Mongo database on startup (to populate the local Minimongo DB) and then fires 'added' event for each item added in the local database.

But is this the normal behavior ? How can I receive only items that are "truly" added in the database on the server ?

like image 462
TiuSh Avatar asked Apr 18 '12 21:04

TiuSh


1 Answers

You are observing a cursor for the client side database and that database may not finish syncing until after the page is done loading, so the behavior makes sense. You may want to look into explicitly subscribing to a collection as discussed in the answer to this question.

If your data had a created_at field then you could observe items created after the page loads.

  ItemCollection.find({created_at : {$gt: some_current_time}}).observe({
    added: function(item) {
      // Alert code
    }
  });
like image 74
lashleigh Avatar answered Oct 30 '22 03:10

lashleigh