首页 > 解决方案 > 如何在 Firebase 中动态更新集合中的文档

问题描述

我已经能够动态创建记录(用户配置文件)并在 Firebase 中检索他们的唯一 ID。

但现在我希望能够让最终用户更新他们的个人资料。虽然我可以检索配置文件的文档 ID aka uid。如何模板化动态获取登录人员的 uid 并更新该特定记录的能力?

我尝试了以下方法:

 async updateProfile() {
    const docRef = await db.collection("users").get(`${this.userId}`);
    docRef.update({
      optInTexts: this.form.optInTexts,
      phone: this.form.mobile
    });
    db.collection("users")
      .update({
        optInTexts: this.form.optInTexts,
        phone: this.form.mobile
      })
      .then(function () {
        console.log("Profile successfully updated!");
      })
      .catch(function (error) {
        console.error("Error updating document: ", error);
      });
  }

`

我也试过

 async updateProfile() {
    const docRef = await db.collection("users").where("userId", "==", `${this.userId}`);
    docRef.update({
      optInTexts: this.form.optInTexts,
      phone: this.form.mobile
    });
    db.collection("users")
      .update({
        optInTexts: this.form.optInTexts,
        phone: this.form.mobile
      })
      .then(function () {
        console.log("Profile successfully updated!");
      })
      .catch(function (error) {
        console.error("Error updating document: ", error);
      });
  }

``

和这个

  async updateProfile() {
    const docRef = await db.collection("users").get(`${this.userId}`);
    docRef.update({
      optInTexts: this.form.optInTexts,
      phone: this.form.mobile
    });
    db.collection("users/`${this.userId}`")
      .update({
        optInTexts: this.form.optInTexts,
        phone: this.form.mobile
      })
      .then(function () {
        console.log("Profile successfully updated!");
      })
      .catch(function (error) {
        console.error("Error updating document: ", error);
      });
  }

错误docRef.update is not a function

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


在查看了这篇文章后,我能够解决这个问题:如何更新单个 firebase firestore 文档

我试图引用的集合是一个用户表,其中包含从 Firebase 开箱即用的 Google 身份验证创建的数据。因此,查询和更新数据与我的其他数据不同,其中 doc ID 等于集合的 uid。工作解决方案:

  async updateProfile() {

    const e164 = this.concatenateToE164();

    const data = {
      optInTexts: this.form.optInTexts,
      phone: e164};

    const user = await db.collection('users')
      .where("uid", "==", this.userId)
      .get()
      .then(snapshot => {
        snapshot.forEach(function(doc) {
          db.collection("users").doc(doc.id).update(data);
        });
      })
  }

推荐阅读