How to delete data from Firestore with cloud functions

Viewed 1827

I'm writing a cloud functions in conjunction with google's Firestore database.

I'm trying to write recursive delete more data. I can't find the syntax for accessing and deleting data in other parts of the database. The code I have already is below.

exports.deleteProject = functions.firestore.document('{userID}/projects/easy/{projectID}').onDelete(event => {
    // Get an object representing the document prior to deletion
    // e.g. {'name': 'Marie', 'age': 66}
    // console.log(event)
    // console.log(event.data)
    console.log(event.data.previous.data())

    var deletedValue = event.data.previous.data();

});

I found some info here but I don't have time to check through it atm, if I find something useful I'll amend the question.

https://firebase.google.com/docs/firestore/manage-data/delete-data?authuser=0

2 Answers

One can use below code to delete all the documents in a collection recursively.
This code worked perfectly for me.
Make sure you have JSON file of firebase credentials and firebase-admin installed.

const admin = require('firebase-admin');
const db = admin.firestore();
const serviceAccount = require('./PATH_TO_FIREBASE_CREDENTIALS.json');
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

deleteCollection(db, COLLECTION_NAME, NUMBER_OF_RECORDS)
async function deleteCollection(db, collectionPath, batchSize) {
    const collectionRef = db.collection(collectionPath);
    const query = collectionRef.orderBy('__name__').limit(batchSize);

    return new Promise((resolve, reject) => {
        deleteQueryBatch(db, query, resolve).catch(reject);
    });
}

async function deleteQueryBatch(db, query, resolve) {
    const snapshot = await query.get();

    const batchSize = snapshot.size;
    if (batchSize === 0) {
        // When there are no documents left, we are done
        resolve();
        return;
    }

    // Delete documents in a batch
    const batch = db.batch();
    snapshot.docs.forEach((doc) => {
        batch.delete(doc.ref);
    });
    await batch.commit();

    // Recurse on the next process tick, to avoid
    // exploding the stack.
    process.nextTick(() => {
        deleteQueryBatch(db, query, resolve);
    });
}    
Related