繁体   English   中英

如何获取 Firestore 文档的自动生成 ID?

[英]How to get the auto generated ID of a Firestore document?

我在创建文档时使用自动生成的 ID。 设置后,我需要得到它。

await admin.firestore().collection("mycollection").doc().set(mydata)  
    .then(doc => {

        console.log(doc.id);

        return true;
     })
     .catch(err => {
         return false;
     });

日志中检索到的 ID 与 Firestore 数据库中的 ID 不同。 我不明白为什么。

日志中检索到的 ID 与 Firestore 数据库中的 ID 不同。

这是正常的,因为set()方法返回一个Promise<void> (即解析为undefined的 Promise )。 因此,您不能在传递给then()方法的回调 function 中执行doc.id ,因为docundefined

您应该执行以下操作:

try {
  const docRef = admin.firestore().collection("mycollection").doc();
  const docId = docRef.id;  //Here you have the value of the id (independently of the fact you call set() later or not)

  await docRef.set(mydata);
} catch(err) {
  //...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM