如何从Firebase获取文档ID

时间:2020-04-07 20:55:47

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

我是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的最佳方法。

谢谢您的帮助!

Blockquote

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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