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?
>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.