/firebase-tutorials

How to prevent duplicate documents in Firestore?

Prevent duplicate documents in Firestore using unique identifiers, effective queries, and robust error handling. Follow our step-by-step guide with code examples.

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 prevent duplicate documents in Firestore?

 

Step 1: Understand the Problem of Duplicates

Before we start implementing the solution, it's crucial to understand why duplicates might be created in Firestore. Duplicates can occur if the same data is unintentionally sent to Firestore multiple times. This could result due to network issues, retry logic, or bugs in your application logic. To prevent duplicates, you will typically use unique identifiers that can ensure a document is only written once into a specific Firestore collection.

 

Step 2: Define a Unique Field for Documents

The first step towards avoiding duplicates is identifying a field in your documents that should be unique. For example, if you have a collection of users, you might choose the email address as a unique identifier. Ensure you have this logic clearly defined as it'll be the key to preventing duplicates.

 

Step 3: Use Firestore Queries to Check for Existing Documents

Before adding a new document to your collection, perform a query to check if a document with the same unique field value already exists.


const checkForExistingDocument = async (firestore, collectionName, uniqueFieldValue) => {
  const querySnapshot = await firestore.collection(collectionName)
                                       .where('uniqueField', '==', uniqueFieldValue)
                                       .get();
  return !querySnapshot.empty;
};

If the query returns any documents, it means a document with that unique identifier already exists.

 

Step 4: Conditionally Add Document

Once you've confirmed that there are no existing documents with the same unique field value, you can safely add the new document.


const addDocumentIfNotExists = async (firestore, collectionName, data) => {
  const { uniqueField } = data;
  
  // Check if the document already exists
  const exists = await checkForExistingDocument(firestore, collectionName, uniqueField);
  
  if (!exists) {
    // Add the document since it doesn't exist
    await firestore.collection(collectionName).add(data);
    console.log('Document added successfully!');
  } else {
    console.log('Duplicate document exists, no new document was added.');
  }
};

This function first checks for an existing document and then adds the new document if it does not already exist.

 

Step 5: Implement Error Handling and Logic in Your Application

Ensure that your application has proper error handling to manage scenarios where document writing fails due to other reasons. Implement retry logic if necessary but ensure it respects the logic for uniqueness checks to prevent adding duplicates during retries.


try {
  await addDocumentIfNotExists(firestoreInstance, 'users', { uniqueField: '[email protected]', ... });
} catch (error) {
  console.error('Error adding document:', error.message);
  // Implement retry mechanism if needed but make sure to keep the uniqueness logic
}

 

Step 6: Consider Cloud Functions for Server-Side Checks

For added security and integrity, you might want to utilize Firebase Cloud Functions to ensure uniqueness on the server-side. This is especially useful if the client-side checks can be bypassed.


const admin = require('firebase-admin');

exports.checkAndAddUser = functions.https.onCall(async (data, context) => {
  const { email } = data;
  const firestore = admin.firestore();
  
  const exists = await checkForExistingDocument(firestore, 'users', email);
  
  if (!exists) {
    await firestore.collection('users').add(data);
    return { success: true, message: 'User added successfully!' };
  } else {
    return { success: false, message: 'User already exists!' };
  }
});

 

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