cursor.observe({added}) behavior in Meteor
Asked Answered
C

1

9

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 ?

Colic answered 18/4, 2012 at 21:46 Comment(0)
N
13

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
    }
  });
Naucratis answered 18/4, 2012 at 23:21 Comment(2)
Awesome! I'm really glad to hear that it helped.Naucratis
Also see the answer to this question: #21356302Propend

© 2022 - 2024 — McMap. All rights reserved.