类型错误:无法读取未定义的属性“_fieldsProto”

Tre*_*son 4 firebase google-cloud-firestore

我正在使用 Firestore,每当我尝试data从查询快照调用文档上的方法时,都会收到此错误。这是我的代码。

  let snapshot: FirebaseFirestore.QuerySnapshot<FirebaseFirestore.DocumentData>;
  try {
    snapshot = await admin.firestore()
      .collection("products")
      .where("email", "==", email)
      .get();
  } catch (error) {
    // error code
  }

  if (snapshot.empty) {
    // does not exist
    return;
  }

  const docs: DbSubscription[] = [];

  snapshot.forEach(({ data, id }) => {
    // this is where error is thrown
    docs.push({ ...data(), id } as DbSubscription);
  });
Run Code Online (Sandbox Code Playgroud)

我确认该文档存在并且具有数据,因为登录snapshot?.docs[0]?.data()到控制台会输出预期的内容。但是调用data上面的方法会引发错误。

任何人都知道为什么会发生这种情况?非常感激!

web*_*ath 9

所以看起来该函数data对对象进行了内部引用this来访问该_fieldsProto对象。当data函数通过解构从文档快照中拉出时,this不再指向文档快照而是指向全局对象。因此_fieldsProto无法找到该对象并抛出错误。

可以通过直接从文档快照调用数据函数来在代码中纠正此问题:

  snapshot.forEach((doc) => {
    const [id, data] = [doc.id, doc.data()];
    docs.push({ ...data, id } as DbSubscription);
  });
Run Code Online (Sandbox Code Playgroud)