Firebase

How to use Firebase Firestore to store and query nested documents?

Learn how to store and query nested documents using Firebase Firestore. Make database management easier with our detailed, easy-to-follow guide.

Developer profile skeleton
a developer thinking

Overview

This piece digs into how to use Firebase Firestore for storing and querying nested documents. Firebase Firestore is a flexible, cloud-based NoSQL database that's perfect for syncing and making app data easily accessible across both mobile and web platforms. But, the idea of nested documents—basically docs inside other docs—can puzzle newcomers. Utilizing nested documents smartly can make your database more organized and efficient. Here, the focus is on revealing the necessary steps to set up and use Firestore for querying and storing these nested documents, helping navigate Firestore's data model smoothly.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to use Firebase Firestore to store and query nested documents?

Importing Firebase in Your Project

Alright, before diving into Firebase Firestore, we need to get Firebase into our project. For a web app, just pop these scripts into your HTML file:

<!-- Firebase App -->
<script src="https://www.gstatic.com/firebasejs/VERSION/firebase-app.js"></script>

<!-- Firebase Firestore -->
<script src="https://www.gstatic.com/firebasejs/VERSION/firebase-firestore.js"></script>

Don't forget to swap out VERSION with the specific version of Firebase you're using.

Initializing Firebase Firestore

Next up, we need to initialize Firebase. Replace your-project-id, your-app-id, and your-api-key with your own Firebase project's details.

const firebaseConfig = {
  apiKey: "your-api-key",
  authDomain: "your-project-id.firebaseapp.com",
  projectId: "your-project-id",
  appId: "your-app-id",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Initialize Firestore
const db = firebase.firestore();

Storing Documents in Firestore

To add a new document to a collection and store some data, use this method:

let data = {
  name: 'John Doe',
  age: 34,
  children: [
    {name: 'Anna Doe', age: 7},
    {name: 'Sarah Doe', age: 5}
  ]
};

db.collection('users').doc('user1').set(data);

Here, users is the collection name, user1 is the document ID, and data is the object with the data you want to store.

Querying Documents in Firestore

To fetch the data stored in a document, you can use the get() function.

db.collection('users').doc('user1').get().then((doc) => {
  if (doc.exists) {
    console.log("Document data:", doc.data());
  } else {
    console.log("No such document!");
  }
}).catch((error) => {
  console.log("Error getting document:", error);
});

If the user1 document exists, its data will be logged in the console. Otherwise, you'll see "No such document!".

Querying Nested Documents in Firestore

To access nested document values, you need to mention the full path to the nested value. Here's how you can get the data from the children array in the stored document.

db.collection('users').doc('user1').get().then((doc) => {
  if (doc.exists) {
    let childrenData = doc.data().children;
    childrenData.forEach(child => {
         console.log("Child's name: " + child.name);
         console.log("Child's age: " + child.age);
    });
  } else {
    console.log("No such document!");
  }
}).catch((error) => {
  console.log("Error getting document:", error);
});

This will log the name and age of each child in the nested 'children' array.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.