rustyBucketBay
rustyBucketBay

Reputation: 4561

Conditinal database record delete firebase

I want to clean some records of a firestore database. I have a function that receives the records I would like to keep, I check in all the records if id is not in the docsToKeep:firebase documents argument. I use a foreach for all the records, and I user filter to find the matching id as shown in the working snippet below:

async function checkForNotifClean(docsToKeep:firebase.firestore.QuerySnapshot<firebase.firestore.DocumentData>) {
  const db = firebase.firestore();
  const notifCollection = db.collection('notifications')
  const allData = await notifCollection.get();
  allData.docs.forEach(doc => {
    const filtered = docsToKeep.docs.filter(entry => entry.id === doc.id); 
    const needsErase = filtered.length === 0;
    if (needsErase) {
      const id = doc.id; 
      notifCollection.doc(id).delete();
    }
  })
}

Is there a cleaner way to erase all the documents that are not in docsToKeep ? Would be kind of function that get all the objects that are not in both arrays and delete those. I would be happy on improvements on the javascript side to filter out the records to delete, and in the firebase side, improvements regarding the chance of deleting some set of records at once instead of looping through all and deleting each.

Upvotes: 1

Views: 35

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

To delete (or write to) a document in Firestore you need to know the complete path to that document, including its document ID. If you don't have the IDs of the documents to delete, then your only option is to determine those IDs as you're doing now.

It does lead to the question how docsToKeep is populated though. My guess it that the user already selects some documents from a full list. If that's the case, might you be able to pass the inverted list: docsToDelete?

Upvotes: 1

Related Questions