【问题标题】:Firebase Firestore update a field in all documentsFirebase Firestore 更新所有文档中的一个字段
【发布时间】:2022-11-25 07:02:46
【问题描述】:

我想为 web 的 firebase firestore 中用户集合中的所有文档更新notf_unread : true

我怎样才能做到这一点..

【问题讨论】:

  • 你能提供你已经尝试过的 sn-p 吗?你用的是第8版还是第9版?请使用此详细信息更新您的问题。

标签: javascript node.js firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

如果您想更新集合中的所有文档。您必须使用集合引用创建查询并迭代查询的所有结果。请参阅下面的示例代码:

版本 8(命名空间):

var db = firebase.firestore();

db.collection("users")
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          doc.ref.update({
              notf_unread: false
          })
          .then(() => {
              console.log("Document successfully updated!");
          })
          .catch((error) => {
              // The document probably doesn't exist.
              console.error("Error updating document: ", error);
          });
        });
    })
    .catch((error) => {
        console.log("Error getting documents: ", error);
    });

版本 9(模块化):

const q = query(collection(db, 'users'))

const querySnapshot = await getDocs(q);

querySnapshot.forEach((doc) => {
    updateDoc(doc.ref, {
        notf_unread: false
    })
    .then(() => {
        console.log("Document successfully updated!");
    })
    .catch((error) => {
        // The document probably doesn't exist.
        console.error("Error updating document: ", error);
    });
})

有关更多信息,您可以访问此文档:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-15
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    相关资源
    最近更新 更多