Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple documents with firebase cloud function

Sorry for the rookie question, but I am about to toss my laptop.

I'm new to js and have been struggling to understand how to use promises.

When a conversation is deleted this function is triggered and should loop throw all the messages contained in the conversation and delete them.

My problem is I don't no where to delete the messages or how to do it. How do I delete the messages?

exports.deleteMessages = functions.firestore
.document('users/{userId}/conversations/{conversationId}')
.onDelete(event => {

    // Get an object representing the document prior to deletion
    const deletedConversation = event.data.previous.data();

    return database.collection('messages')
        .where('conversationId', '==', deletedConversation.id).get()
        .then(snapshot => {

            snapshot.forEach(document => {
                const data = document.data();
                database.collection('messages').document(data.id).delete();
            });

            return console.log("Don't even no why I'm returning this")
        })
        .catch(error => {
            console.log('Error when getting document ' + error)
        });
});
like image 254
user3116871 Avatar asked May 02 '26 13:05

user3116871


1 Answers

You have to use Promise.all(), which "returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises."

You should do along these lines:

const promises = [];

return database.collection('messages')
    .where('conversationId', '==', deletedConversation.id).get()
    .then(snapshot => {

        snapshot.forEach(document => {
            //Create a Promise that deletes this document
            //Push the Promise in the "promises" array
            promises.push(deleteDocPromise(document))

        });
        //and return: 
        return Promise.all(promises);
    })
    .then(
      //Do whatever you want in case of succesfull deletion of all the doc
    )
    .catch(error => {
        ....
    });

In order to create the Promise for deletion do something like

function deleteDocPromise(document) {
        //using the code of your question here
        const data = document.data();
        return database.collection('messages').doc(data.id).delete();   
}
like image 51
Renaud Tarnec Avatar answered May 04 '26 03:05

Renaud Tarnec