TypeError: Cannot read property '_fieldsProto' of undefined

Viewed 592

I am using Firestore and am getting this error whenever I try to call the data method on a document from a query snapshot. Here is my code.

  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);
  });

I confirmed that the document exists and has data because logging snapshot?.docs[0]?.data() to the console outputs what is expected. However calling the data method above throws the error.

Anyone have a clue why this might be happening? Much appreciated!

1 Answers

So it appears that the function data makes an internal reference to the this object to access the _fieldsProto object. When the data function is pulled out of the document snapshot through destructuring, this no longer points to the document snapshot but to the global object. Thus the _fieldsProto object cannot not be found and an error is thrown.

This issue can be rectified in your code by calling the data function directly from the document snapshot:

  snapshot.forEach((doc) => {
    const [id, data] = [doc.id, doc.data()];
    docs.push({ ...data, id } as DbSubscription);
  });
Related