【问题标题】:How to get the document id from a firebase如何从 Firebase 获取文档 ID
【发布时间】:2020-04-07 20:55:47
【问题描述】:

我是 Angular 新手,但我遇到了问题。我不知道如何获取我刚刚创建的文档 ID 并在它旁边使用它。我看到有db.collection('info').doc().set()db.collection('info').add()两个选项。

目前我已经尝试过这段代码:

var DocID:string;
db.collection().add({
   description: info
  }).then(function(docRef){
   DocID = docRef.id;
  }).catch(function(error){
   console.log("Error creating the document:", error);
});
IdInfo.push(DocID);

我需要将文档中的所有 Id 存储在数组中,尽管有时我完成了它,而其他时候我收到错误 undefined。我不知道哪种方法是创建新文档并向其添加数据并接收文档 ID 的最佳方式。

谢谢你的帮助!!

块引用

【问题讨论】:

    标签: angular firebase ionic-framework google-cloud-firestore


    【解决方案1】:

    add() 返回一个Promise,因此您可以使用then(),它将包含一个回调,当Promise 完成时将调用该回调。由于Promise 用于异步操作,所以这里IdInfo.push(DocID); 将得到未定义,因为数据仍未完全检索。您需要在then() 中添加上述代码才能在数组中添加docID

    db.collection().add({
       description: info
      }).then(function(docRef){
       DocID = docRef.id;
       IdInfo.push(DocID);
      }).catch(function(error){
       console.log("Error creating the document:", error);
    });
    

    【讨论】:

      【解决方案2】:

      这两个选项在功能上是等效的。选择您喜欢的那个。

      如果您使用add(),它将返回一个带有生成文档 ID 的 DocumentReference。如果您使用doc()(在调用set() 之前),它还将返回一个DocumentReference(在使用set() 编写文档之前)。请务必阅读每种方法的 API 文档以了解它们的作用。

      【讨论】:

        猜你喜欢
        • 2020-11-02
        • 2019-12-31
        • 1970-01-01
        • 2021-05-06
        • 1970-01-01
        • 1970-01-01
        • 2023-01-18
        • 2018-09-03
        • 1970-01-01
        相关资源
        最近更新 更多