/firebase-tutorials

How to get document ID in Firestore?

Learn how to retrieve Firestore document IDs with step-by-step instructions on initializing Firebase, fetching documents, and adding data with auto-generated or custom IDs.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to get document ID in Firestore?

 

Step 1: Set up Firebase in your Project

 

Before you can access Firestore, you must set up Firebase in your project. First, ensure that you have a Firebase project created by going to the Firebase Console.

  1. Add Firebase to your app by following the onboarding flow provided in the Firebase Console.
  2. Download the google-services.json file for Android or GoogleService-Info.plist for iOS and place it in your project according to the instructions.
  3. For web applications, include Firebase libraries via script tags or by installing Firebase using npm.

 

Step 2: Initialize Firebase in Your Project

 

You need to initialize Firebase in your application to access its services like Firestore.

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

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Firestore
const db = getFirestore(app);

 

Step 3: Get Document ID in Firestore

 

To retrieve document IDs in Firestore, you need to access documents within a collection. Assume a collection named users.

import { collection, getDocs } from "firebase/firestore";

const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
  console.log(`${doc.id} => ${JSON.stringify(doc.data())}`);
});

In this snippet:

  • The collection function is used to specify the Firestore collection.
  • getDocs fetches all documents in the specified collection.
  • forEach iterates through each document and retrieves the document ID using doc.id along with the document data using doc.data().

 

Step 4: Get Specific Document ID When Adding Data

 

When adding a new document to Firestore, the document ID can be automatically generated or specified by you.

To auto-generate a document ID:

import { collection, addDoc } from "firebase/firestore";

const docRef = await addDoc(collection(db, "users"), {
  name: "John Doe",
  email: "[email protected]"
});

console.log("Document ID: ", docRef.id);

To specify a document ID yourself:

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

await setDoc(doc(db, "users", "customDocId"), {
  name: "John Doe",
  email: "[email protected]"
});

console.log("Document added with ID: customDocId");

 

Step 5: Conclusion

 

Understanding how to retrieve document IDs in Firestore is key to accessing and managing your data effectively. Whether you are iterating over collections or adding new entries, knowing how to handle document IDs allows for better data manipulation and querying. Make sure to handle asynchronous calls using async/await as demonstrated for smooth and efficient data operations.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022