本文介绍了Meteor中的cursor.observe({added})行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当数据添加到数据库时,我试图向用户显示警报.所以我写了(在客户端):

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

并且我发现,当将新项添加到服务器端的数据库中时,不仅会显示警报(我认为这是正常的:)),而且刷新页面时,还会为每个先前添加的项显示警报.我假设Meteor在启动时会从Mongo数据库中获取所有数据(以填充本地Minimongo DB),然后为本地数据库中添加的每个项目触发添加"事件.

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 ?

推荐答案

您正在观察客户端数据库的游标,并且该数据库可能直到页面完成加载后才能完成同步,因此该行为很有意义.您可能希望根据此问题.

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.

如果您的数据具有created_at字段,则可以观察页面加载后创建的项目.

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

这篇关于Meteor中的cursor.observe({added})行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:38