只收听 Cloud Firestore 集合的新增内容? [英] Listen only to additions to a cloud firestore collection?

查看:27
本文介绍了只收听 Cloud Firestore 集合的新增内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,当我尝试在 firestore 中的集合上使用实时侦听器时,每次将新文档添加到集合中时,都会重新运行逻辑,并且我将下载集合中已有的所有内容

现在:

firebase.firestore().collection("Tweets").onSnapshot(function(querySnapshot) {querySnapshot.forEach(function(doc) {console.log("添加了快照", doc)});});

有没有办法只跟踪集合的添加?我想我可以做那个设备端,但没有必要传输我已经查询的所有额外数据..

该日志的输出将打印出集合中的每一条推文",无论是否只添加了一条推文

例如:初始查询

-推文 1

-推文 2

-推文 3

新推文,已添加推文 4

输出:

推文 1

推文 2

推文 3

推文 4

如果有道理

解决方案

当您使用 onSnapshot() ,您实际上并没有在每次调用时下载整个集合.文档被缓存,当集合再次改变时将被重用.

对于导致调用回调的每个更改,您可以通过检查快照中的更改来找出自第一次调用以来哪些文档是新看到的.如何执行此操作的示例是在文档中.有了查询快照,您就可以使用此逻辑来确定哪些文档是新文档:

snapshot.docChanges.forEach(function(change) {if (change.type === "已添加") {//change.doc 这里是新建一个新文档}});

I've noticed, when I try to use a realtime listener on a Collection in firestore, each time a new Document is added to the collection, the logic will be rerun, and I will download everything already in the collection

right now:

firebase.firestore().collection("Tweets").onSnapshot(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
        console.log("snapshot added ", doc)
      });
    });

Is there a way to track only ADDITIONS to the collection? I guess I could do that device side, but theres no need to transfer all the additional data I have already queryed for..

Output of that log would print out every single "tweet" in the collection, regardless of only one being added

EX: Initial Query

-Tweet 1

-Tweet 2

-Tweet 3

New Tweet, Tweet 4 is added

Output:

Tweet 1

Tweet 2

Tweet 3

Tweet 4

If that makes sense

解决方案

When you use onSnapshot() on a collection, you're not actually downloading the entire collection on each invocation. The documents are cached and will be reused when the collection changes again.

For each change that causes your callback to be invoked, you can find out which documents are new seen since the first invocation by checking the changes within the snapshot. An example of how to do this is in the documentation. With a query snapshot in hand, you can use this logic to determine which documents are new:

snapshot.docChanges.forEach(function(change) {
    if (change.type === "added") {
        // change.doc here is new a new document
    }
});

这篇关于只收听 Cloud Firestore 集合的新增内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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