Home > Blockchain >  Firebase: Delete documents without a subcollection inside them
Firebase: Delete documents without a subcollection inside them

Time:04-14

I have a collection named "departments" with a subcollection inside named "users". I want to delete all the documents in "departments" without documents in the users sub-collection or without the sub-collection users.

Any ideas of how to find the documents to delete?

Thanks!

CodePudding user response:

Assuming you have a structure that looks like this:

Firestore-root
  |
  --- departments (collection)
        |
        --- $departmentId (document)
               |
               --- users (collection)
                    |
                    --- $uid (document)
                         |
                         --- //user data

To be able to achieve this:

I want to delete all the documents in "departments" without documents in the users sub-collection.

You have to get all documents in the users sub-collection and delete them. But remember, such an operation is not really recommended by the Firebase team to be done on the client, if you have a large number of documents inside your collection. However, for a small number of documents, it will work.

The most important thing in this operation is that if you delete those documents, the sub-collections will continue to exist, and deleted documents will be displayed in italic.

Only in the Realtime Database, if you delete a node, you delete it with all the data that exists beneath it. But here is not the case, so no worries.

CodePudding user response:

To be able to delete documents that don't have subcollection, you must query the departments collection and iterate the documents to check whether they have the subcollection users on it. See sample code below:

const db = getFirestore();

// `departments` reference.
const departmentsRef = query(collection(db, "departments"));
// Gets all documents from the department's reference.
const querySnapshot = await getDocs(departmentsRef);

// Iterate the documents.
querySnapshot.forEach(async (doc) => {

  // `users` reference.
  const usersRef = query(collection(db, "departments", doc.id, "users"));
  
  // Check if the document has the `users` collection
  const querySnapshot = await getDocs(usersRef)
  .then((usersDoc) => {
    
    // Check if the `users` subcollection exists
    // Also counts the documents of the subcollection. 
    if (!usersDoc.size) {
      // Deletes the document from the document reference.
      deleteDoc(doc.ref);
    }
  });
});
  • Related