1

For the context I'm using firebase/nodeJS on my application.

I'm deleting an user of a collection called workers. To do so I update the field deleted : true on the worker document. I'm not deleting the document, because I want to keep their infos if needed. But when I delete a worker, I must remove him from all the properties is working on (they have a field called workers, which is an array of all the workers associated.)

Hence, I must browse all the properties of the collection associated, check if the worker is on it and remove him.

Is there a way to do so ? I saw this page : https://firebase.google.com/docs/firestore/manage-data/add-data#node.js_11 But don't know how to use theses ressources to do so.

Raphael Lopes
  • 141
  • 2
  • 14
  • It sounds like you want to run a query to find all the documents in the collection that have a reference to the document that you're deleting. Renaud showed an example of how to do that here: https://stackoverflow.com/a/53141199 – Frank van Puffelen Oct 07 '21 at 13:32
  • 1
    i made it, I will answer my own question later today! – Raphael Lopes Oct 07 '21 at 14:29

1 Answers1

0

So I finally did it alone. First, I had to fetch all the properties where the work is working on, to do this I used array-contains.

let docsProperties = await db.collection('user').doc(id).collection("properties")
            .where("workers", "array-contains", workerId).get();

Then I wanted to browse all theses properties and remove the worker. Thought about doing a ForEach first. But the problem is I wanted to use an await .update() with arrayRemove and async methods aren't usable inside ForEach. So I used promises.

            let promises = [];

        docsProperties.forEach(doc => {
            promises.push(doc.ref.update({
                workers: admin.firestore.FieldValue.arrayRemove(workerId)
            })); });
        return Promise.all(promises);

arrayRemove is a method from the firebase documentation to remove all the occurences of an element on a following array field. So I browsed all properties, added all promises and executed them!

worked perfectly, if anyone got questions don't hesitate.

Raphael Lopes
  • 141
  • 2
  • 14