Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

cursor.observe({added}) behavior in 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...