流星中的 cursor.observe({add}) 行为 [英] cursor.observe({added}) behavior in Meteor

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

问题描述

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆