How to add multiple documents to a collection in Firebase

Firebase is a popular backend solution developers use to build and improve scalable applications.


Firebase offers several services, such as hosting, cloud storage, etc. Firestore is part of the many services offered by Firebase. Firestore is relevant for cloud-based applications and has multiple other features. One of these is the ability to add multiple documents to a collection in Firebase.

Cloud Firestore

Firebase has a feature called Cloud Firestore, a versatile NoSQL document database that lets us store and sync data in real-time. It also has the features below:

  • It allows developers to store, sync, and query application data.

  • It is a flexible, scalable database that allows developers to store data in a hierarchical format, similar to JSON.

  • It is part of the Firebase platform, a suite of backend services for mobile and web applications.

  • It has collections and groups of documents that share a common structure. It is similar to a table in a traditional relational database. A collection can contain any number of documents, each with its own unique fields and data.

Adding a single document to a Firebase collection is straightforward, but adding multiple documents can be challenging and differ significantly.

Code example

We can add multiple documents to a collection in Firestore by using the following steps:

  1. Add multiple documents to a collection in Firebase by executing multiple write operations, like the batch write operation.

  2. Execute multiple operations as a single batch that contains any combination of operations, such as set(), update(), or delete().

    The following code snippet shows how to go about a batch write.

Note: To use this program, we need to meet some prerequisites. Specifically, we must have a Firebase project set up and configured with Firestore. Detailed instructions for setting up firestore can be found in the How to set up Firestore answer.

Source Code

// Import the Firebase SDK and initialize Firebase
const firebase = require("firebase/compat/app");
require("firebase/compat/firestore");

const firebaseConfig = {
  // Your Firebase project configuration
  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",
  measurementId: "YOUR_MEASUREMENT_ID"
};

firebase.initializeApp(firebaseConfig);

const db = firebase.firestore();

// Get a reference to the collection
const collectionRef = db.collection("collections");

// Define the data for the documents
const dataArray = [
  { name: "John", role: "Teacher" },
  { name: "Jane", role: "Artist" },
  { name: "Bob", role: "Gym Instructor" },
];

// Create a batch write operation
const batch = firebase.firestore().batch();

// Loop through the data array and add each document to the batch
dataArray.forEach((data) => {
  const docRef = collectionRef.doc(); // Create a new document reference with a unique ID
  batch.set(docRef, data); // Add the data to the batch for this document reference
});

// Commit the batch write operation
batch
  .commit()
  .then(() => {
    console.log("Batch write operation completed");
  })
  .catch((error) => {
    console.error("Batch write operation failed: ", error);
  });
Adding multiple documents to a collection

Code explanation

Let's understand the code bit by bit:

  • Line 2-3: This code imports the Firebase app and Firestore modules using the require() method.

  • Line 5-14: This code defines an object firebaseConfig which contains the configuration settings for a Firebase project, including the API key, authentication domain, project ID, storage bucket, messaging sender ID, app ID, and measurement ID.

  • Line 16: This code initializes the Firebase application using the configuration object firebaseConfig that contains the necessary settings for connecting to a Firebase project, allowing the application to interact with other Firebase services like Firestore.

  • Line 18: This code creates a db variable that references the Firestore database associated with the Firebase application instance created by firebase.initializeApp(). This allows you to use the Firestore API to interact with the database, such as reading, writing, and updating data.

  • Line 21: This code creates a reference to the Firestore collection named collections in the database associated with the db variable.

  • Line 24-28: This code creates an array of JavaScript objects, dataArray, where each object contains two properties: name and role, which will be used to add data to the Firestore database.

  • Line 31: This line of code creates a new batch of write operation using the firebase.firestore() method and the batch() method. This allows us to write multiple Firestore operations as a single unit, which can be more efficient and atomic than writing each operation individually.

  • Line 34-37: This code uses a forEach loop to iterate over each object in the dataArray, and for each object, it creates a new document reference with a unique ID using the collectionRef.doc() method, and then adds the data to the batch for this document reference using the batch.set() method.

  • Line 40 -47: This code commits the batch write operation to the Firestore database and logs a success message to the console if it succeeds or logs an error message if it fails.

Free Resources