如何使用 React/Firestore 获取单个文档?

ydr*_*rea 2 javascript firebase reactjs google-cloud-firestore

我想做的就是从数据库中获取一行(所谓的“doc”)。

到目前为止,我已经尝试过:

全部带有“aref”

  const aref = firebase
    .firestore()
    .collection("polja")
    .where("id", "==", match.params.id);
  console.log(aref);

  function getIt() {
    const item = [];
    setLoading(true);
    aref.get().then((doc) => {
      const data = doc.data();
      setItem(item);
      console.log(item);
      setLoading(false);
    });
  }
  
  useEffect(() => {
    getIt();
  }, []);


Run Code Online (Sandbox Code Playgroud)

这给出了以下错误:

错误

数据库结构

Dha*_*raj 9

要获取单个文档,您必须指定文档 ID:

firebase.firestore().collection("polja").doc(documentId).get().then((snapshot) => {
  console.log(snapshot.data())
}).catch((e) => console.log(e))
Run Code Online (Sandbox Code Playgroud)

另外,您不应该用来.where()获取单个文档,但我在您的原始代码中发现了一个问题。

仔细一看,里面的参数.where()是一个字符串"match.params.id"。这似乎是从其他地方获取的动态值。请删除引号并重试。

firebase.firestore().collection("polja").where("id", "==", match.params.id).get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch((error) => {
        console.log("Error getting documents: ", error);
    });
Run Code Online (Sandbox Code Playgroud)

尝试添加一个 catch 块,如图所示,这可能有助于捕获任何错误。确保您的安全规则也允许您获取数据。此外,如果控制台中记录了任何错误,请分享它的屏幕截图。


Tar*_*epp 6

要从 firebase firestore 获取单个文档,您应该首先知道您使用的是模块化 firebase 9.+ 版本还是 firebase 版本 < 9。

在新的模块化 firebase firestore(版本 9.+)中,它应该是这样的:

import { getFirestore, collection, query, getDocs } from 'firebase/firestore'
async read(id) {
  const firestore = getFirestore()
  const docRef = doc(firestore, this.collectionPath, id)
  const docSnap = await getDoc(docRef)

  const data = docSnap.exists() ? docSnap.data() : null

  if (data === null || data === undefined) return null

  return { id, ...data }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是非模块化 Firebase firestore(< 版本 9),则相同的函数应如下所示:

async read(id) {
  const result = await (await firestore())
    .collection(this.collectionPath)
    .doc(id)
    .get()

  const data = result.exists ? result.data() : null

  if (data === null || data === undefined) return null

  return { id, ...data }
}
Run Code Online (Sandbox Code Playgroud)