Tips for simultaneously updating a value in multiple collections on firestore?

Currently, I am in the process of developing a forum application using Vue, which is essentially a replica of this platform. In this app, users can post questions, receive answers to those questions, and leave comments on those answers. Each question, answer, and comment has a corresponding document in a top-level collection, with a field called photoURL where the profile image URL of the author is stored.

I have implemented code to update the photoURL field in each document belonging to the same author across all three collections when that user updates their profile picture:

const QUESTIONS = db.collection("questions");
QUESTIONS.where("authorId", "==", this.user.data.id)
.get()
.then(snapshots => {
    if (snapshots.size > 0) {
        snapshots.forEach(questionItem => {
            QUESTIONS.doc(questionItem.id).update({
                photoURL: imgUrl
            });
        });
    }
});

const ANSWERS = db.collection("answers");
ANSWERS.where("authorId", "==", this.user.data.id)
.get()
.then(snapshots => {
    if (snapshots.size > 0) {
        snapshots.forEach(answerItem => {
            ANSWERS.doc(answerItem.id).update({
                photoURL: imgUrl
            });
        });
    }
});

const COMMENTS = db.collection("comments");
COMMENTS.where("authorId", "==", this.user.data.id)
.get()
.then(snapshots => {
    if (snapshots.size > 0) {
        snapshots.forEach(commentItem => {
            COMMENTS.doc(commentItem.id).update({
                photoURL: imgUrl
            });
        });
    }
});

The current implementation is functional, but I am exploring more efficient ways to execute these operations simultaneously or discover an improved method for handling these updates. One thought was to first store all retrieved IDs from the three collections in an array and then perform the updates, but it seems that the number of write operations would remain constant, thus not providing a significant enhancement.

Answer №1

Here are two strategies that come to mind:

  1. Minimize redundant code.
  2. Revise the data structure.

Minimize redundant code

You could create a utility function that takes the collection to be updated as a parameter:

function updateDocumentsInCollectionForAuthor(collection, author, update) {
  db.collection(collection).where("authorId", "==", author)
    .get()
    .then(snapshots => {
      snapshots.forEach(doc => {
        doc.ref.update(update);
      });
    });
}

Although batching updates like Doug suggested may offer performance benefits, the added complexity likely outweighs the gains. Take a look at this discussion for more insights: What is the fastest way to write a lot of documents to Firestore?

You can then use this function to update each collection:

updateDocumentsInCollectionForAuthor("questions", this.user.data.id, { photoURL: imgUrl });
updateDocumentsInCollectionForAuthor("answers", this.user.data.id, { photoURL: imgUrl });
updateDocumentsInCollectionForAuthor("comments", this.user.data.id, { photoURL: imgUrl });

Revise the data structure

Another option is to reconfigure your data model to consolidate all questions, answers, and comments in a single collection. This approach mirrors Stack Overflow's setup where diverse items are stored in one table distinguished by their post type.

Answer №2

Is there a more efficient method to execute these three operations simultaneously?

One alternative is to bundle all the updates together and execute a batch operation, although this may not enhance the process unless you prefer all updates to be dependent on each other.

Are there any other approaches to efficiently handle these updates?

In order to determine what works best, it's important to consider your definition of "efficient". The available options for updating a document include: 1) using update() or set() with merge, 2) batch writing, and 3) transactions. Choose the method that aligns best with your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting window size when page is resized

While browsing through SO, I stumbled upon this interesting piece of code: var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w. ...

The behavior of the jQuery click function seems to be quirky and not functioning as expected. Additionally, the

It seems that instead of triggering a POST request, somehow a GET request is being triggered. Additionally, the ajax call is not being made as expected. I have attempted this many times before, but none of my attempts seem to be working. It could potenti ...

How come the mongoose ref feature is not functioning properly for me when I attempt to reference objects from a different schema?

I'm having trouble accessing the attributes of a store's address, as I keep getting 'undefined'. It seems that the address is only an id, even though I set up a 'ref' in the address schema. What could be causing this issue? H ...

What is the process of integrating ES6 modules with app.get in a Node/Express routing application?

After researching the benefits of ES6 export, I made the decision to implement it in a NodeJS/Express project instead of using module exports. The MDN documentation explained that export is used as shown below: export function draw(ctx, length, x, y, color ...

Modify a field within MongoDB and seamlessly update the user interface without requiring a page refresh

I am currently working on updating a single property. I have various properties such as product name, price, quantity, supplier, and description. When sending the updated quantities along with all properties to MongoDb, I am able to update both the databas ...

Ways to insert HTML text into an external webpage's div element without using an iframe

Is it possible to generate HTML and SVG code based on the position of a Subscriber on a web page or within a specific div? I would like to provide some JavaScript code that can be inserted inside a particular div on the page. Using an iframe is not ideal ...

What is the equivalent of preg_replace in PHP using jquery/javascript replace?

One useful feature of the preg_replace function in PHP is its ability to limit the number of replacements made. This means that you can specify certain occurrences to be replaced while leaving others untouched. For example, you could replace the first occu ...

Using a Javascript library within an Angular component: A comprehensive guide

I've been working on a Web-Client project that involves visualizing sensor data such as velocity and acceleration within a coordinate system. In order to display this coordinate system, I decided to use the graph.js library from https://github.com/dhu ...

A guide on ensuring all necessary keys are present in a JSON document using Node.js

I have been researching various methods for efficiently checking if a key exists in a JSON file. The challenge I am facing is related to optimizing this process. My current workflow involves users uploading a CSV file which I then convert into JSON format ...

Exploring object properties within arrays and nested objects using ReactJS

Within the react component PokemonInfo, I am looking to extract the stats.base_stat value from the JSON obtained from https://pokeapi.co/api/v2/pokemon/1/. The issue lies in the fact that base_stat is nested inside an array called stats. My assumption is t ...

Display issue with React TypeScript select field

I am working with a useState hook that contains an array of strings representing currency symbols such as "USD", "EUR", etc. const [symbols, setSymbols] = useState<string[]>() My goal is to display these currency symbols in a select field. Currently ...

When the Ionic app is relaunched from the side menu, the view fails to refresh

When I open my Side Menu, I initially see two options - scan barcode or search product. Once I choose one, the rest of the view is filled in dynamically. The issue arises when I try to go back to the Side Menu and reload the view to only display the origin ...

What is the importance of context in the subscription method of RxJS or Angular Observables?

In the given situations, I am providing a child Component with a property that is updated later through an RxJs Observable subscription. Angular fails to detect changes when not using an anonymous function or binding the this context. // Situation 1 // C ...

($rootScope: busy) Applying changes right now

Whenever I try to make changes to the UI grid after refreshing the data, I keep encountering this error message: angular.js:13236 Error: [$rootScope:inprog] $apply already in progress http://errors.angularjs.org/1.5.0/$rootScope/inprog?p0=%24apply ...

What is the best way to determine if any of the list items (li's) have been marked as selected?

<div id='identifier'> <ul id='list'> <li id='1' class="">a</li> <li id='2' class="">a</li> <li id='3' class="">a</li> <li id='4' class=" ...

Button to save and unsave in IONIC 2

I am looking to implement a save and unsaved icon feature in my list. The idea is that when I click on the icon, it saves the item and changes the icon accordingly. If I click on it again, it should unsave the item and revert the icon back to its original ...

Displaying a table in Chrome/Firefox with a mouseover feature

Hovering over the rows of this table triggers a display of descriptions. html: <tr title="{{transaction.submissionLog}}" class="mastertooltip">... JavaScript: $('.masterTooltip').hover(function(){ // Hover functionality ...

When retrieving data from a PHP $_SESSION using an Ajax $_POST call, outdated information is being returned

I am encountering an issue that I cannot seem to figure out. Currently, my application consists of three pages: Home.php Nearmiss.php Reports.php Each of these pages includes code at the top with a specific "thispage" variable unique to that page. < ...

What is the best way to display values from a Localstorage array in a tabular format using a looping structure

I have set up a local storage key 'fsubs' to store form submissions as an array. Here is how I am doing it: var fsubs = JSON.parse(localStorage.getItem('fsubs') || "[]"); var fcodes = {"barcodeno" : this.form.value.barcode, "reelno" : ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...