Angular 2中通过id获取Firestore文档

19

如何在Google Firestore中按ID获取文档?是否有get()方法可用?我已经搜索了,但没有找到适合我的正确答案:(

更新:对我来说this.itemscollection.doc(id).get()没有起作用。

2个回答

29

尝试这段代码

this.itemscollection.doc(id).ref.get().then(function(doc) {
  if (doc.exists) {
    console.log("Document data:", doc.data());
  } else {
    console.log("No such document!");
  }
}).catch(function(error) {
  console.log("Error getting document:", error);
});

为什么需要ref?我看了很多的例子,没人用它,所以每次都出现同样的错误:“get不是一个函数”。请解释一下。 - sirandy
@sirandy 你在使用angularfire2吗? - Hareesh
@sirandy 我相信angularfire2会在firebase类周围创建一个包装器。这就是为什么你需要.ref来获取doc.exists,它是一个firebase函数。 - Hareesh
1
在我的最新测试中,.ref 是不必要的。 - Shanqing Cai
你如何设置集合?这在哪个文档中可以找到?什么是.ref,为什么它不在任何文档中? - Joshua Foxworth

7

在使用 angularFire2 包与 firestore 进行开发时,成功的关键在于要知道所有官方文档中操作单个文档(如 'get'、'set'、'update') 的 firestore 方法都是 'ref' 方法的子方法。

 firestore - this.itemscollection.doc(id).get() 
 angularfirestore2 - this.itemscollection.doc(id).ref.get()
-------------------------------------
 firestore - this.itemscollection.doc(id).set()
 angularfirestore2 - this.itemscollection.doc(id).ref.set()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接