Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve document ID in firestore firebase

I am trying to retrieve the document ID in firestore database, I have successfully retrieved the data but not the ID for each document. Here is my code to retrieve the document data :

  const ref = query(
    collection(db, "vehicles"),
    where("type", "==", "motorbike")
  );
  onSnapshot(ref, (categories) =>
    setMotorList(categories.docs.map((doc) => doc.data()))
  );
  console.log(motorList);
} catch (e) {
  alert("failed load data " + e);

firebase config :

import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import {
  getAuth,
  initializeAuth,
  getReactNativePersistence,
} from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth();

export default app;

How should I modify my code to retrieve the ID from vehicles database?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The get the document ID, you can use the snapshot‘s doc.id property like in the following lines of code:

onSnapshot(ref, (categories) =>
  categories.docs.map((doc) => ({id: doc.id, ...doc.data()}))
                               //👆
)

Please note that I have added the ID as a property to the object.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading