What is the best method for updating a specific data field in Firestore with Firebase Modular SDK V9?

Currently, I am working on updating data to send a number to another user's number.

const updateNumber = async(e) => {
        e.preventDefault();
        
        
        const targetQuery = query(userCollection, where("keycode", "==", parseInt(target)));
        const targetSnapshot = await getDocuments(targetQuery)
        
        targetSnapshot.forEach((document) => {
            console.log(document.data().num)
            console.log(document.id)
            const targetReference = doc(database, 'users', document.id)

            setDoc(targetReference, {
                num: // increment the user's data here
            }, {merge: true})
        })
}

Unfortunately, I have come across documentation that is hard to understand and some information I grasp is already outdated. Any help or guidance on this would be greatly appreciated :)

Answer №1

If you need guidance on incrementing a numeric value in Firestore, refer to the dedicated section in the documentation titled increment a numeric value.

import { setDoc, increment } from "firebase/firestore";

await setDoc(targetRef, {
    num: increment(50)
});

To avoid using await within a forEach loop (since setDoc returns a promise that must be awaited), consider utilizing either Batch Writes or Promise.all().

For more insights on using async/await with a forEach loop, check out this resource on Stack Overflow.

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

Designing Angular web elements within Angular

Although Angular natively supports Web components, I am unsure about how to style a web component with SCSS without the styles affecting the hosting page. When rules are defined in a component's .scss files, they should only apply to that specific co ...

Showing a heading based on a value in Angular: A Complete Guide

I am attempting to dynamically change the title based on the item's _id value. I have stored the item in the component. Here is the HTML code I am using: <h1 mat-dialog-title>{{item._id ? "Update" : "Add"}} animal</h1> Below is my dialog ...

What is the proper way to include <script> using Prototype?

Currently, I am utilizing the Prototype insert function to append some HTML that includes <script>...</script>. Inside this script, a new function is being defined. According to what I have read here, Prototype executes the script within <sc ...

The execution of res.sendFile has been terminated, redirecting me to localhost:XXXX/?

In my application, I have set up a route that is being accessed, confirmed by the console.logs. However, the issue lies with the res.sendFile function at the end, as it is not directing me to the intended location. Instead, it redirects me to localhost:XXX ...

Adaptable material for collapsible panels

I'm facing a challenge with implementing an accordion menu. My goal is to have a 4 column layout that transforms into an accordion menu when the browser width is less than 600px. It almost works as intended, but there's a glitch. If you start at ...

Tips for Rotating an Object and Returning it to its Original Orientation

An issue with the turnover arises as the axis is connected to the geometry. View now: Rotate now: Rotation required: ...

Refreshing JqGrid tables after making changes and saving a row

In my PHP file, I have 4 jqGrid tables where I pass a different JSON array for each table. The data displayed on the grids come from one table with various SQL conditions. I am using inline editing for all the grids. After editing and saving a row in tabl ...

Tips for executing an Angular controller prior to DOM initialization

I have some code in my Angular controller that I want to run when the document is ready, but Angular currently runs it as the DOM is being created. While this does produce the correct output, it also generates console errors because initially the image src ...

The jQuery AJAX function is not functioning properly when using an ASP.net server side

Having issues with my code. The jquery ajax is not functioning properly. Here is my jquery script: $('#AddPermission').click(function () { var _permissionId = $('#PermissionId').val(); var _roleId = $('#Role_Id& ...

Leveraging an HTML file to interact with a Google Spreadsheet via a Textbox input for executing queries with the help of App

I'm working with a spreadsheet that has over 1000 lines, each column representing a field. One of the columns is labeled "Domain," which is the value I need to query. My HTML application needs to have a text box where users can input a domain, and the ...

What is the best way to retrieve the desired Angular GET format from an Express server?

As I work on developing an Express server (localhost:3000) and an Angular application to retrieve values, I have encountered an interesting issue. Despite specifying the GET header as "text/html", the result displayed in the Angular console always appears ...

What is the best way to transfer a JavaScript variable to a JSON format?

Hey there! I'm diving into the world of coding and eager to learn. Recently, I successfully passed a query parameter into a JavaScript variable using the following code: const queryString = window.location.search; console.log(queryString); const urlPa ...

Tips on handling the vertices of an object that has been loaded using ObjLoader in Three.js

I have loaded an object in my scene using ObjLoader. However, I am struggling to read the vertices of that object. I can easily read and modify the vertices of a normal cube created in three.js, but it doesn't seem to work on the object loaded by ObjL ...

Breaking data in Ionic 3 and displaying it using the Angular trunk option

When fetching data from an API, I encountered some wordings that are contained within a single string. To display them separately, here's how they appear in the console: https://i.sstatic.net/daZHV.png However, I would like to present them in my app ...

Tips for upgrading chart js in Vue application?

I am having an issue with updating a chart by clicking on a button. Although the data changes in the store, the UI does not reflect the update. <div class="graph"> <button class="click" @click="changeUi">Update Chart</butto ...

Showing particular URL text upon opening a new window using JavaScript

I've encountered an intriguing scenario. In my application, there's a feature that triggers a new window/tab to open when a button is clicked. Upon opening, a predefined HTML page is shown to the user with a specific URL set. I'm curious abo ...

Extracting key values from JSON using Node.js

Trying to read a json file using nodejs and locating a specific key within the object is my current task: fs.readFile('./output.json', 'utf8', function(err, data) { if (err) throw err; console.log(Object.keys(data)); } ...

Change classes of sibling elements using Angular 2

Imagine you have the following code snippet: <div id="parent"> <div class="child"> <div class="child"> <div class="child"> </div> I am looking to automatically assign the class active to the first child element. ...

What is the best way to animate CSS elements using jQuery to slide in from the right, left, or bottom?

When the page is scrolled on my website, I want table_area-left to move from left to right to its current position, table_area-right to move from right to left to its current position, and morph button to move from down to up. I am struggling to find the j ...

What could be the reason for the token being undefined on the client side?

I have built an ecommerce site using nextjs and mongoose, integrating a jwt token in a cookie for client-side authentication. However, when trying to retrieve the token from the cookie named OursiteJWT, I encountered issues with it being undefined: https: ...