首页 > 解决方案 > 为什么 snap.data().id 没有定义?

问题描述

我似乎无法获得要检索的文档的 ID。

我在网上看了很多例子,他们似乎都在做我正在做的事情。

exports.moveToProfile = functions.firestore
  .document("tempProfiles/{id}")
  .onCreate(async (snap, context) => {
    const id = snap.data().id;
    const displayName = snap.data().displayName;

    const profile = await db
      .collection("profiles")
      .doc(id)
      .set({
        displayName: displayName,
        points: 0
      });

    return profile;
  });

标签: javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


在您的代码中,dataDocumentSnapshot类型的对象。从链接的 API 文档中可以看到,该对象表示的文档的 ID 是它的id 属性。data() 为您提供其所有字段(正式文档 ID 不是其中之一,除非您将其写为字段。)因此,您可以使用data.id.


推荐阅读