如何使用 Firebase JS SDK 版本 9 按 ID 查找文档?

The*_*ple 5 javascript firebase google-cloud-firestore

Firebase JS SDK 的新版本 9 已经推出,采用了更加模块化的方法,我正在尝试了解它。

我想通过 ID 从 Firestore 查找并读取文档。在版本 8 中,您可以执行以下操作:

await db.collection('users').doc(id).get();
Run Code Online (Sandbox Code Playgroud)

版本 9 似乎有一个名为“doc”的函数和一个名为“getDoc”的函数,这听起来像是新的等效函数,但我不明白如何在实践中使用它们。还有其他人玩过这些吗?

提前致谢!

Dha*_*raj 4

文档有一个完整的代码片段,解释了如何获取具有给定 ID 的单个文档:

import { doc, getDoc } from "firebase/firestore";

const docRef = doc(db, "users", id);
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Document data:", docSnap.data());
} else {
  // doc.data() will be undefined in this case
  console.log("No such document!");
}
Run Code Online (Sandbox Code Playgroud)

doc()方法用于获取 DocumentReference用于getDoc()从给定引用中获取文档。