firestore 快照是否可以包含 x 个已更改的文档

Can a firestore snapshot contain x number of changed documents

我想问一下 Firestore

阅读the docs

添加、删除或修改文档后,我会在文档的这段代码中收到有关该事件的信号:

db.collection("cities").where("state", "==", "CA")
    .onSnapshot((snapshot) => {
        snapshot.docChanges().forEach((change) => {
            if (change.type === "added") {
                console.log("New city: ", change.doc.data());
            }
            if (change.type === "modified") {
                console.log("Modified city: ", change.doc.data());
            }
            if (change.type === "removed") {
                console.log("Removed city: ", change.doc.data());
            }
        });
    });
  1. 当我启动这个侦听器时,我会得到所有匹配 "state", "==", "CA" 的文档,即使它是 100.000 个吗?他们是一次全部来还是分批来?

  2. 在上面的初始所有 (100.000) 之后我总是会得到一 (1) 个文档,比如当文档被修改、添加或删除时,或者是否会有像批量折叠延迟从 firestore 所以我会在快照中得到一对多?

当您第一次 运行 查询时,您将获得与该查询匹配的所有内容,并带有 change.type === "added"。然后您将收到所做的更改,一个接一个(除非有人一次写了一批)。

管理这个的方法是在集合中添加一个过滤器。例如,您可能希望按日期字段或名称字段对集合进行排序。然后将结果限制在可管理的数字和 paginate.

db.collection("cities")
    .where("state", ">=", "CA")
    .orderBy("state")
    .limit(50)
    .onSnapshot((snapshot) => {
        snapshot.docChanges().forEach((change) => {
            if (change.type === "added") {
                console.log("New city: ", change.doc.data());
            }
            if (change.type === "modified") {
                console.log("Modified city: ", change.doc.data());
            }
            if (change.type === "removed") {
                console.log("Removed city: ", change.doc.data());
            }
        });
    });

不要忘记添加一个 unsubscribe 以便您可以删除侦听器

您只获得 added/modified/removed 的文档,但是文档清楚地说明第一次设置侦听器时它将 return 所有匹配的文档文档。

The first query snapshot contains added events for all existing documents that match the query. This is because you're getting a set of changes that bring your query snapshot current with the initial state of the query. This allows you, for instance, to directly populate your UI from the changes you receive in the first query snapshot, without needing to add special logic for handling the initial state.

所以他们一直都在。之后它们将只是更改,即更改的文档数量。

The initial state can come from the server directly, or from a local cache. If there is state available in a local cache, the query snapshot will be initially populated with the cached data, then updated with the server's data when the client has caught up with the server's state.

话虽如此,如果数据来自服务器而不是本地缓存,您可能需要为此付费。