Firestore更新集合中的所有文档

Lio*_*l B 5 redux google-cloud-firestore

我有一个名为用户的消防站集合,每个用户都有一个生成的ID和一个字段得分:

users 
    0e8X3VFL56rHBxxgkYOW
        score : 4
    3SeDjrgAWMmh3ranh2u
        score : 5
Run Code Online (Sandbox Code Playgroud)

我使用redux-firestore,我想将所有用户的得分重置为0,例如

firestore.update({ collection: 'users' }, { score : 0 }
Run Code Online (Sandbox Code Playgroud)

我无法实现,因为更新方法需要文档ID

你知道怎么做吗?

jsa*_*ter 14

由于某种奇怪的原因,接受的答案( thehamzarocks )对我不起作用,没有任何文件被更新。也许 AngularFire2 中存在错误。无论如何,我决定遍历 QuerySnapshot 的 docs 数组而不是使用它的 forEach 方法,并将每个更新添加到批处理队列中。批处理批量操作也比为每个更新操作发送一个新的更新请求更有效。

resetScore(): Promise<void> {
  return this.usersCollectionRef.ref.get().then(resp => {
    console.log(resp.docs)
    let batch = this.afs.firestore.batch();

    resp.docs.forEach(userDocRef => {
      batch.update(userDocRef.ref, {'score': 0, 'leadsWithSalesWin': 0, 'leadsReported': 0});
    })
    batch.commit().catch(err => console.error(err));
  }).catch(error => console.error(error))
}
Run Code Online (Sandbox Code Playgroud)


the*_*cks 8

您可以获取集合中的所有文档,获取其ID并使用这些ID执行更新:

db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        var cityRef = db.collection("cities").doc(doc.id);

        return cityRef.update({
            capital: true
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

  • @AbdulrahmanAbdelkader 除了这个答案所建议的之外,没有其他办法。我必须阅读所有文档并使用循环进行更新。 (5认同)
  • 我的集合中有大约 100 万个文档,我想更新所有文档中的一个属性。最好的方法是什么?100 万份文档,数千名用户实时使用该应用程序。我想阅读所有这些内容并更新将花费大量的读取和写入。 (4认同)
  • @RobertWilliams 那么你做了什么?我在类似的船上 (4认同)