Home > Net >  Firebase Firestore, How to update multiple collection from array of objects efficiently
Firebase Firestore, How to update multiple collection from array of objects efficiently

Time:11-25

i have this firestore collection that needs to update according to the data within array of objects, at first this was not a problem. but as the data grows. to update the data to firebase is we have to compare each id and then perform update to all of the data.

here i have some array,

let newCategoriesUpdate = [
{
    category_id: 100001,
    parent_category_id: 0,
    name: "Health",
    isActive: true,
    has_children: true,
  },
  {
    category_id: 100019,
    parent_category_id: 100001,
    name: "Medical Equipment",
    isActive: true,
    has_children: false,
  },
  {
    category_id: 100020,
    parent_category_id: 100001,
    name: "Laboratory",
    isActive: false,
    has_children: false,
  },
]

the list contains more than 200 objects which need to compare on each loop, which takes more time and memory.

Here's what i've implemented in firebase to update the collection from array of objects above


const handleUpdateCategories = () => {
    db.collection("category")
      .get()
      .then((snapshot) => {
        snapshot.forEach((docRef) => {
          let name = "My Category";
          if (docRef.data().name === name) {
            let categoryRef = docRef.id;
            db.collection("category")
              .doc(categoryRef)
              .collection("categoryList")
              .get()
              .then((snapshotCollection) => {

                // loop collection from firebase
                snapshotCollection.forEach((catListDocRef) => {
                  let categoryListRefId = catListDocRef.id;

                  // need to compare each loop in array
                  // loop array to update

                  newCategoriesUpdate.map((category) => {
                    if (
                      catListDocRef.data().categoryId === category.category_id
                    ) {
                      db.collection("category")
                        .doc(categoryRef)
                        .collection("categoryList")
                        .doc(categoryListRefId)
                        .set(
                          {
                            categoryId: category.category_id,
                            isActive: category.isActive,
                            categoryName: category.name,
                          },
                          { merge: true }
                        )
                        .then(() => {
                          console.log("UPDATE Success");
                        })
                        .catch((err) => {
                          console.log("ERR", err);
                        });
                    }
                  });
                });
              });
          }
        });
      });
  };

This method works, and in the console also shows the message "UPDATE Success" multiple times.

Is there a better alternative to update multiple collection from array of objects?

CodePudding user response:

This is wasteful:

db.collection("category")
  .get()
  .then((snapshot) => {
    snapshot.forEach((docRef) => {
      let name = "My Category";
      if (docRef.data().name === name) {
        ...

You're retrieving all documents from category and then only processing the ones that have "My Category" as their name. If there are documents with other names, you should use a query to retrieve only the ones you need to process:

db.collection("category")
  .where("name", "==", "My Category")
  .get()
  .then((snapshot) => {
    snapshot.forEach((docRef) => {
      ...

There may be more things, but this is the first that jumped out at me.

CodePudding user response:

This work can be done on the server side with a cloud function onWrite trigger listening to the Categories collection.

Also consider structuring your data more efficiently, can you store the child category in the parent so you know exactly which documents need to be updated?

  • Related