添加文档并向该文档添加子集合Firestore

时间:2020-08-17 04:51:26

标签: javascript firebase google-cloud-firestore

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应用程序。我在控制台中收到以下错误:“未捕获(承诺)TypeError:t.collection不是函数”。我猜想我在then函数-> {code: this.state.code, words: []}中引用Firestore文档-> db.collection("rooms").where("code", "==", this.state.code)时还没有创建它。关于如何在保持Firestore调用顺序的同时解决此错误的任何建议?

2 个答案:

答案 0 :(得分:0)

当您在此处Query对象上调用array时:

get()

它将返回一个产生QuerySnapshot对象的Promise。该对象上没有名为db.collection("rooms").where("code", "==", this.state.code).get() 的方法。它包含您必须处理的查询结果。

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

collection()

我建议还回顾一下关于Firestore查询的documentation以及上面链接的API文档。

答案 1 :(得分:0)

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)的帮助下,该实现得以实现。