【问题标题】:Adding a document and adding a sub-collection to that document Firestore添加文档并将子集合添加到该文档 Firestore
【发布时间】:2020-08-17 04:51:26
【问题描述】:
db.collection("rooms").add({
        code: this.state.code,
        words: []
      }).then(() => {
        db.collection("rooms").where("code", "==", this.state.code).get().then((doc) => {
          doc.collection("players").add({name: this.state.name, votes: 0}).then(() => {
            socket.emit("createGroup", this.state.code);
          });
        });
    });

我正在使用客户端 Firestore 调用和 SocketIO 构建一个 React/Express 应用程序。我在控制台中收到以下错误:“Uncaught (in promise) TypeError: t.collection is not a function”。我猜当我在 then 函数中引用 Firestore 文档 -> {code: this.state.code, words: []} 时,不知何故尚未创建它 -> db.collection("rooms").where("code", "==", this.state.code)。关于如何在保持 Firestore 调用顺序的同时修复此错误的任何建议?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    当您在 Query 对象上调用 get() 时:

    db.collection("rooms").where("code", "==", this.state.code).get()
    

    它将返回一个产生QuerySnapshot 对象的承诺。该对象没有名为collection() 的方法。它包含您必须处理的查询结果。

    您将不得不迭代或以其他方式处理该查询的结果以继续前进。您的代码还应该为该查询不返回任何文档的情况做好准备。使用 QuerySnapshot 上的 docs 数组属性了解发生了什么。

    db.collection("rooms").where("code", "==", this.state.code).get().then(querySnapshot => {
      querySnapshot.docs.forEach(snapshot => {
        // handle each document individually, if any
      })
    });
    

    我建议还查看有关 Firestore 查询的 documentation,以及我在上面链接的 API 文档。

    【讨论】:

    • 好吧,这很有意义,感谢您的回答!因此,如果我按照您的建议对该文档进行查询快照,那么我可以从快照中调用该文档的集合方法吗?
    • 是的,您可以从文档快照中获取文档引用并从那里构建路径。
    【解决方案2】:
    db.collection("rooms").add({
            code: this.state.code,
            words: []
          }).then(() => {
            db.collection("rooms").where("code", "==", this.state.code).get().then((querySnapshot) => {
              querySnapshot.docs.forEach((snapshot) => {
                snapshot.ref.collection("players").add({name: this.state.name, votes: 0}).then(() => {
                socket.emit("createGroup", this.state.code);
              });
            });
        });
      });
    

    在 Doug 的帮助下,此实现得以运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2018-07-30
      • 2018-07-22
      相关资源
      最近更新 更多