DEV Community

Antoine for Itself Tools

Posted on

Querying Firestore for Capital Cities with JavaScript

At, we have gained extensive experience working with modern tech stacks, particularly Next.js and Firebase, to build over 30 sophisticated applications. This experience has provided us with a deep understanding of how to effectively utilize databases like Firestore to manipulate and retrieve data efficiently.

What Does This Code Do?

Let's examine the JavaScript snippet below and dissect what each line is responsible for:

const db = getFirestore();
const citiesRef = collection(db, 'cities');
const queryRef = query(citiesRef, where('capital', '==', true));
const querySnapshot = await getDocs(queryRef);
querySnapshot.forEach(doc => {
  console.log(, ' => ',;
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation

  1. Initialize Firestore Database: const db = getFirestore(); This line initializes and returns a reference to the Firestore database instance.
  2. Reference a Collection: const citiesRef = collection(db, 'cities'); Here, we're referencing the 'cities' collection stored in the Firestore database.
  3. Create a Query: const queryRef = query(citiesRef, where('capital', '==', true)); This line creates a query object that looks for documents within the 'cities' collection where the field 'capital' is equal to true, effectively filtering for capital cities.
  4. Execute the Query: const querySnapshot = await getDocs(queryRef); This asynchronous function fetches the documents that satisfy the query's conditions.
  5. Process Query Results: The results of the query are processed in a loop: querySnapshot.forEach(doc => { console.log(, ' => ',; });, where each document's ID and data are logged to the console.

Insights on Using Firestore with JavaScript

Working with Firestore and JavaScript together can greatly enhance your applications, allowing real-time data synchronization and efficient data retrieval methods. The integration of Firestore with async-await in JavaScript promises high-performance data fetching which is critical in modern web development.


To see the practical implementation of the concepts discussed, check out some of our innovative apps like high-capacity temporary emails, online rhyming dictionary, and words translation explorer. These applications showcase real-world usage of Firestore in conjunction with other modern technologies to deliver rich and interactive user experiences.

If you're looking to integrate similar functionalities into your applications, whether they deal with real-time data or complex queries, Firestore paired with JavaScript offers a powerful solution.

Top comments (0)