Creating or accessing maps using TypeScript and Cloud Functions in Firebase

In my document, there is a map referred to as "map" with a specific structure:

-document
   -map
      {id: number}
      {id2: number2}

When the function first executes, only the document exists and I need to create the map with an initial entry.

Before the first execution:

-document

After the first execution:

-document
   -map
      {id: number}

Subsequent executions with an id will increment the stored number in the map. If the id does not exist in the map, it will be inserted.

For example, executing it with id2 would result in the initial structure shown above.

await admin.firestore().runTransaction(async t => {
   const documentDb = await admin.firestore().doc(`document/${documentId}`).get()
   const document = documentDb.data()!
   if (document.map === undefined || document.map[id] === undefined) {
      const tempMap = {}; 
      tempMap[id] = 1
      document.map = tempMap
   } else {
      document.map[id] = document.map[id] + 1
   }
   t.update(documentDb.ref, document);
}

This approach seems simple, but it encounters issues during compilation, specifically at tempMap[id] = 1 due to an implicit "any" type in Typescript. Is there a way to resolve this issue?

Answer №1

To tackle the issue with the "any" type, you can simply use <code>const tempMap : { [key: string]: any } = {}
.

Furthermore, remember not to fetch the document using

documentDb = await admin.firestore().doc(`document/${documentId}`).get()
, but instead utilize the get() method of the transaction:

const documentRef = admin.firestore().doc(`document/${documentId}`);
const snapshot = await t.get(documentRef);
const document= snapshot.data()!;
//...

Update: How to modify the map

const id = ...;
const updatePath = 'map.' + id;    // or id.toString(10) 
const obj = {};
obj[updatePath] = document.map[id] + 1;
t.update(documentDb.ref, obj);

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

Activate fullscreen mode in Krpano on desktop by clicking a button

Is there a way to activate fullscreen mode upon clicking a button? I believe I should use the code: krpano.set(fullscreen,true); Currently, I have an image within a slideshow that includes a play button overlay. Once the button is clicked, the slideshow ...

Populate Vue components in auto-generated HTML code

Utilizing a WYSIWYG article editor, I generate HTML content for articles that is saved in the database and displayed to users at a later time. However, I am facing an issue where I need to embed Vue components within this generated HTML in order to showca ...

retrieving data from a different controller in AngularJS

Having an issue with passing data from rootScope.reslogin2 to scope.user. It's not displaying as expected, here is my JavaScript file: app.controller("logincont", ['$scope','$http','md5','$window','$rootS ...

What is the best way to transfer values between various methods within a single service file in Angular?

In my service file, I have two methods called getData and delete. The data is sourced from an API and the getData method works fine. However, I am facing a problem with the delete() method where siteId is not being read correctly. When I click the save bu ...

Steps for inserting an image onto a blank page

Struggling with HTML and javascript - need help with displaying an image on a new page: Creating a new page and want to show an image on it: thepage= window.open('', '', 'height=700,width=800,left=100,top=100,resizable=yes,scroll ...

Ways to execute multiple functions in synchronization within react js

I have a method called componentDidUpdate() in my code, where I have two functions implemented: componentDidUpdate(prevProps){ if (prevProps !== this.props){ this.getListHistory() this.forceUpdate() } } The this.getListH ...

Is it possible to encounter an unusual token export while trying to deactivate Vue with veevalidate

Utilizing Nuxt with server side rendering. Incorporating Typescript along with vee-validate version 3.4.9. The following code has been validated successfully extend('positive', value => { return value >= 0; }); Upon adding the default, ...

Guide to testing express Router routes with unit tests

I recently started learning Node and Express and I'm in the process of writing unit tests for my routes/controllers. To keep things organized, I've split my routes and controllers into separate files. How should I approach testing my routes? con ...

When I apply filtering and grouping to the table, the rows in the mat table disappear

When using mat-table, grouping works fine without filtering. However, once the table is filtered or if the search bar is focused, ungrouping causes the rows in the table to disappear. I am looking for a solution that allows me to group and ungroup the tabl ...

Elements that are hidden or not displayed are still able to receive mouse over events

I am in the process of learning how to handle events within svgs and I have encountered a strange issue. Currently, I am working on an infovis project where I create an interface to display various column-graphs. This part is functioning well so far. Ho ...

Is there a way to reset the canvas with just a click of a button?

How do I reset the canvas upon button click? I attempted: cx.fillRect() However, the above method did not work as expected. I simply want to refresh the canvas without reloading the entire page. Below is my current code snippet: var canvas = docum ...

Is there a way in asp.net to enable users to switch a textbox to a grid view by clicking a button on the webpage?

I currently have a multiline textbox for users to input text. I want to give them the option to switch this textbox to a grid layout when they click a button labeled "Switch to Grid". How can I replace the textbox with a grid layout in the same location ...

The issue with the `this` keyword in a jquery event handler when using Typescript

Here is my TypeScript code snippet. class something { createSomething(): JQuery { let result = $('<div>'); $('<input>').on('change paste keyup', () => { this.myProperty = $(this) ...

Issue: Custom Object is returning an error stating that the property 'forEach' does not exist on type 'void'.ts(2339)

Within my code, I am dealing with a variable that can be either of type User or void. The dilemma arises when the code runs into an error message saying: Property 'forEach' does not exist on type 'void'.ts(2339). Despite trying various ...

Attempting to implement a typeguard in Typescript that relies on the presence of specific content within an element

Currently, I am attempting to develop a Typescript conditional that verifies if a particular word is already present in the name. The function in question is as follows: isOrganic() { for (let i = 0; i < this.items.length; i++) { if(this.ite ...

"Double the Data: A D3.js JSON Tale of Two Creators

I found inspiration from this example: http://bl.ocks.org/mbostock/1062288 to create a collapsible Force Layout. One challenge I'm facing is how to display a graph where a single node is connected to two parent nodes. father father | | ...

a guide to effortlessly updating data in ng2-charts in real-time using Firebase

I am brand new to using angular2. My current challenge involves creating a bar chart with the ng2-charts library and connecting it to firebase through angularfire2. I have developed 2 components and a service that is responsible for sending and receiving d ...

Node 14 introduces a new feature that allows modules to be imported using absolute paths for native ES6 modules

As I develop an app in node version 14.9.0, the need for importing modules arises. To make the process cleaner and more organized, I have configured my ES6 module with "type": "module" in my package.json. My goal is to implement absolut ...

Tips for implementing AngularJS on a webpage transfer

I am a beginner in learning AngularJS. I have gone through the basic tips on W3Schools, but now I am stuck on implementing the login function. When I click the "sign in" button, the webpage should redirect to the login page of the website. However, I am ...

Issue with Vue.js 2.0 transition not triggering on changing routes dynamically

I've encountered an issue where transitions are not firing on dynamic routes with parameters. For example, when navigating from /chapter/1 to /chapter/2, no transition occurs. However, when going from /chapter/1 to /profile/1, a transition does occur! ...