如何从 firebase 获取单个元素

How to get single element from firebase

我从 firebase 数据库中获取所有数据,并将其显示在列表中。现在,当我点击一个特定元素时,我想要做什么,只获取该特定元素的所有数据。 我正在使用 Next.js/react.js 管理 firebase 连接的基本文件

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app"

import { getFirestore } from "@firebase/firestore"
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "A#########################I",
  authDomain: "clion-project.firebaseapp.com",
  projectId: "clion-project",
  storageBucket: "clion-project.appspot.com",
  messagingSenderId: "8#########",
  appId: "1:86735948933:web:46352###############",
  measurementId: "G-KZG7P8MRW2",
}

// Initialize Firebase
const app = initializeApp(firebaseConfig)
export const db = getFirestore(app)

我如何获取元素列表:

const usersCollectionRef = collection(db, "Patients") 
const [user, setUsers] = useState([])
const q = query(usersCollectionRef)
  onSnapshot(q, (QuerySnapshot) => {
    setUsers(
      QuerySnapshot.docs.map((doc) => ({
        id: doc.id,
        data: doc.data(),
      }))
    )
  })

现在如何使用其 ID 从列表中查询特定元素?

假设您有特定的元素文档 ID,您可以这样做:

const docRef = doc(db, "Patients", "<your element doc id>");
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Doc data:", docSnap.data());
} else {
  console.log("doc doesn't exists");
}