Update all documents within a Firestore collection

In my firestore database, I have a collection named users. Each user has a unique ID and a corresponding score:

users 
    0e8X3VFL56rHBxxgkYOW
        score : 4
    3SeDjrgAWMmh3ranh2u
        score : 5

I am utilizing redux-firestore and I am trying to reset all the users' scores to 0. I attempted the following:

firestore.update({ collection: 'users' }, { score : 0 }

However, this did not work as the update method requires a document ID.

Do you have any suggestions on how I can achieve this?

Answer №1

To retrieve all documents within a collection, extract their unique identifiers, and carry out updates based on these identifiers:

db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        doc.ref.update({
            capital: true
        });
    });
});

Answer №2

After encountering issues with the accepted answer provided by thehamzarocks, which failed to update any documents for me, I suspected a possible bug in AngularFire2. To work around this issue, I decided to iterate over the docs array of the QuerySnapshot and enqueue each update operation into a batch queue. This method proved to be more efficient than sending individual update requests for each document.

resetScores(): Promise<void> {
  return this.usersCollectionRef.ref.get().then(response => {
    console.log(response.docs)
    let batch = this.afs.firestore.batch();

    response.docs.forEach(userDocReference => {
      batch.update(userDocReference.ref, {'score': 0, 'leadsWithSalesWin': 0, 'leadsReported': 0});
    })
    batch.commit().catch(error => console.error(error));
  }).catch(err => console.error(err))
}

Answer №3

When utilizing batch updates, it's important to remember that there is a limit of 500 document updates per transaction. If this reset operation is not performed frequently, one simple approach would be:

async function resetScores() {
  const collection = await db
    .collection("users")
    .get()
  collection.forEach(doc=> {
    doc.ref
      .update({
        score: 0
      })
  })
}

Answer №4

While exploring for solutions, I stumbled upon this post. Firestore has introduced batched writes now, allowing updates to multiple documents in a single operation. This feature can be beneficial when dealing with a smaller number of documents.

Expanding on @thehamzarocks's response:

A new batch is created using const batch = db.batch()

db.collection('cities').get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        const docRef = db.collection('cities').doc(doc.id)
        batch.update(docRef, { capital: true })
    });

    The changes are then committed by calling batch.commit();
});

Answer №5

Unfortunately, Firestore lacks the capability to perform bulk updates on documents without specifying their IDs. In order to update multiple documents, you will need to have prior knowledge of each document's ID and update them individually either by querying for them or batching queries.

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

Include a variety of links in an unordered list, with only the initial link triggering a click event

When presenting the user with a choice between two links, I want them to be able to select either one and have it navigate to the corresponding destination. However, in my current setup, no matter which line they click on, it always redirects to the first ...

Data-bind knockout select knockout bind data

Hello! I am a beginner at using knockout and I have encountered an issue with data-binds and the "option" binding. My goal is to display two drop downs populated with data from my database. Surprisingly, I have managed to get the first drop down working pe ...

Analyze the information presented in an HTML table and determine the correct response in a Q&A quiz application

I need to compare each row with a specific row and highlight the border accordingly: <table *ngFor="let Question from Questions| paginate: { itemsPerPage: 1, currentPage: p }"> <tr><td>emp.question</td></tr> <tr> ...

Next.js API route is showing an error stating that the body exceeds the 1mb limit

I'm having trouble using FormData on Next.js to upload an image to the server as I keep getting this error. I've tried various solutions but haven't been able to resolve it yet. This is my code: const changeValue = (e) => { if (e.target ...

Error Message: Error Code 2. I am encountering an issue with the bot expecting either undefined or null and receiving a string primitive instead. Any

As I delved into creating a music bot with support for slash commands, everything seemed to be going smoothly when embedding a URL to a single song. However, the trouble began when attempting to include a link to a playlist, resulting in two perplexing err ...

An error occurred: Unable to access the 'indexOf' property of an undefined variable within the angularjs framework

Hello world of coding, I am a newbie seeking help from experts. The angularJs error I've encountered in the file has been identified and is related to this code snippet: if( searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){ Your assi ...

Identifying Touch Interaction exclusively on WebGL Canvas within threejs

Currently, I am developing a threejs application that requires input from HTML buttons and utilizes Raycast Detection on touch within threeJS. The issue I am encountering is that when the user clicks an HTML button, the Raycast function is triggered as we ...

Grab and drop into place

I have been searching for solutions, but so far I haven't found anything that works for my specific case. I have an upload button that currently works on a click event, but I also want it to be able to drag and drop files for uploading. Here is the H ...

Manipulating properties with JavaScript within a PHP environment

I have been using the code below to modify the display attribute for some of my input tags. echo '<style type="text/css"> #Save{display:none;}</style>'; Now, I am attempting to use a similar approach to set whether an input is disab ...

Issue with passing Redux store to the component props

Struggling with my journey in learning Redux and React. I've set up the store, passed it to the <Provider> using react-redux, but all I see is an empty object when checking the console. import { createStore, applyMiddleware } from 'redux&a ...

What is the best way to eliminate the default hover effect using the MenuItem Mui class?

My goal is to eliminate the default gray hover over animation when using the MUI menu item class. I have attempted several methods, but none have been successful so far. Here are a couple of examples: <MenuItem divider sx={{'&:hover':{bac ...

Awesome method of redirecting outdated URLs to the most recent established URL

My website heavily relies on JavaScript and communicates with a .NET C# RPC service. We encountered an issue where clients' browsers cached the JavaScript, so we decided to add a version number to the URL in order to force them to use the latest JavaS ...

The access-control-allow-origin header is failing to receive updates

I need help figuring out how to manually set the Access-origin header. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge& ...

Toggle element visibility upon clicking

<table id="selectsupp"> <tr> <td> <select id="category"> <option value="display" readonly="true">-Shop By Category-</option> <option value="all">All</option> <option val ...

Retrieve a result from a setTimeout function

Can someone assist me with storing the status value in a variable named 's'? Any help would be greatly appreciated. Below is the code snippet: let s = setTimeout( ()=>{ this.matchService.getMatches().subscribe(ms => { this.match ...

SyntaxError: Identifier was not expected

I am currently working on a function that involves a table of rows with edit buttons. Whenever the edit button is clicked, the following function is called and I encounter this error: Uncaught SyntaxError: Unexpected identifier The error seems to be poin ...

Is it commonplace for redux to generate an abundance of storage?

I'm noticing a lot of lines in the terminal, is it really necessary to create so many storage instances? 4. The WrappedApp just created a new store with withRedux(MyApp) { initialState: undefined, initialStateFromGSPorGSSR: undefined } 14:47:39.619 ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

Display the list of cities associated with the country chosen in the form

I am currently working with the repository found at https://github.com/country-regions/country-region-data/blob/master/data.js to create a mapping of countries and their related cities. I'm seeking guidance on how to achieve this task effectively. My ...

When using Facebook Graph API version 2.2 in conjunction with passport.js, the profile picture may not be returned

During my implementation of Facebook authentication in node.js using passport.js, I have encountered an issue with fetching the user profile picture. I have attempted a few different methods to resolve this problem: user.facebook.picture = profile.user_ph ...