In Firestore, numerical values are stored as string data types

This function is utilized to transmit data to Firestore

exports.professional = functions.https.onRequest((request, response) => {
    const db = admin.firestore();

    const userId: string = request.body['userId'];
    const qualificationId: number = request.body['qualificationId'];
    const occupationId: number = request.body['occupationId'];
    const employmentType: EMPLOYMENT_TYPE = request.body['employmentType'];
    const collegeOrInstitution: string = request.body['collegeOrInstitution'];

    return db.collection('profiles').doc(userId)
        .set(
        {
            professional: {
                qualifaicationId: qualificationId,
                occupationId: occupationId,
                employmentType: employmentType,
                collegeOrInstitution: collegeOrInstitution
            }
        },
        {
            merge: true
        }).then(writeResult => {
           return response.json(
                {
                    status: 1,
                    message: 'Professional details saved successfully',
                    result: userId
                }
            )
        });
});

Although I have designated certain variables as numbers, they are being stored as strings in the Firestore document. Please refer to the screenshot below:

https://i.sstatic.net/ClyLy.png

In the code, despite declaring occupationId as a number variable, it appears as a string after being saved. Could someone explain why this data type change is occurring?

Answer №1

When making declarations in TypeScript, such as:

const occupationId: number

simply declaring a variable does not automatically convert the passed data if the assignment type is any (this is to allow for a gradual transition from JavaScript to TypeScript).

If you specifically need a number, you must use a method that will convert the actual value type for you.

One way to achieve this is by:

const occupationId: number = Number(request.body['occupationId']);

For more information, you can refer to:

Answer №2

Before assigning a value to an object, it is essential to validate whether the value is a number or a letter. If it is a number, one must ensure that it is in the correct numerical format; otherwise, the variable can be passed on unchanged.

+value || value

For instance:

const banana = "Banana"
const quantity = "10"
const getValidValue = (val) => +val || val

console.log(getValidValue(banana))
console.log(getValidValue(quantity))

console.log(typeof getValidValue(banana))
console.log(typeof getValidValue(quantity))

This approach helps Firestore interpret the data type accurately and can be applied to all object variables by iterating through Object.keys.

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

Encountered a style group error 'non-collision' while using Angular with HERE Maps JS API 3.1

Occasionally, I encounter an error when trying to load a HERE map with the satellite base layer: Tangram [error]: Error for style group 'non-collision' for tile 13/16/15542/12554/15 Cannot read property 'retain' of undefined: TypeE ...

Turn off the incorrect TypeScript error detection

After setting up 'interact.js' using jspm and npm for TypeScript compatibility, I am encountering errors in my code: import { interact } from 'interact.js/interact' // ==> typescript error: TS2307: Cannot find module 'interact. ...

react state change not triggering re-render of paragraph

I recently started learning react and web development. To streamline my work, I've been using ChatGPT, but I'm facing an issue that I can't seem to solve. I'm trying to fetch movie descriptions from the TMDB API using movie IDs, but des ...

TypeScript errors undetected by ESlint

I am currently working on a nextJS app with typescript in VSCode. I've noticed that while VSCode accurately displays TS errors when I open a file with an error, the eslint doesn't seem to do the same. For instance, here are the errors shown in m ...

Typescript is failing to compile classes in a reliable sequential order

In my MVC 5 project, I am using TypeScript and angular. There are three TS files: Controller1.ts, Controller2.ts, and app.ts. The issue arises when I compile the program for the first time - everything usually compiles correctly in the expected order. Howe ...

Can you set up a mechanism to receive notifications for changes in an array variable in Angular?

I'm exploring methods to delay an HTTP request until the user stops interacting. I am considering using the debounceTime() operator from RxJs, but I need this to be triggered by changes in an array that I have defined. Here is the scenario: export c ...

Utilizing WebPack 5 in conjunction with Web workers in a React/Typescript environment

Can someone help me figure out how to make a web worker function properly with create-react-app, Typescript, and Webpack 5? I've been struggling with limited documentation and can't seem to find a clear explanation. I'm trying to avoid using ...

Is it possible to dynamically create an interface using an enum in TypeScript through programmatically means?

Recently, I defined an enum as shown below: enum EventType { JOB, JOB_EXECUTION, JOB_GROUP } Now, I am in need of creating an interface structure like this: interface EventConfigurations { JOB: { Enabled?: boolean; }; JOB_EXECUTION: { ...

What are the appropriate scenarios to utilize the declare keyword in TypeScript?

What is the necessity of using declare in TypeScript for declaring variables and functions, and when is it not required? For instance, why use declare var foo: number; when let foo: number; seems to achieve the same result (declaring a variable named ...

Angular progress bar with dynamic behavior during asynchronous start and stop

Currently, I am facing an issue with the progress bar functionality while utilizing the ng-bootstrap module. The scenario involves a dropdown menu with multiple options, and my desired behavior includes: The ability to start/stop the progress bar indepen ...

The Ionic framework lacks support for the firebase and auth properties found in Firebase

Currently, I am developing a user-generated content feature along with buttons using ionic 5 and integrating it with the firebase app. I have been studying posts to incorporate them into my application. I am utilizing: "firebase": "^8.1.1&q ...

Calling functions dynamically in Angular 2

I am facing an issue where I have a function name stored in a variable and I am trying to assign that variable to a click event of a button, but it doesn't seem to be working. Can anyone provide assistance with this? @Component({ selector: 'my ...

Angular 4: Dealing with undefined returns from Observables

Let's start off by clarifying that this situation does not involve an http request. Instead, it's a much simpler scenario where one component sets a boolean value and another component displays or hides an element based on it. The issue at hand ...

Exploring the syntax of typescript when using createContext

Just starting out with typescript and I have some questions. Could someone break down the syntax used in this code snippet for me? What is the significance of having two groups containing signIn, signOut, and user here? Is the first group responsible fo ...

Developing an exportable value service type in TypeScript for AngularJS

I have been working on creating a valuable service using typescript that involves a basic switch case statement based on values from the collection provided below [{ book_id: 1, year_published: 2000 }, { book_id: 2, year_publish ...

Error in unit testing: Trying to access property 'pipe' of an undefined variable results in a TypeError

Recently, I've been faced with the challenge of writing a unit test for one of the functions in my component. The specific function in question is called 'setup', which internally calls another function named 'additionalSetup'. In ...

Accepting undefined in rest parameter of typescript

I'm struggling with an exercise involving Function parameters: The maximum function below has the wrong type. To allow undefined in the rest arguments, you need to update the type of the rest parameter. Fortunately, you don't have to change the ...

Leverage process.env variables within your next.config.js file

Currently, I have an application running on NextJS deployed on GCP. As I set up Continuous Deployment (CD) for the application, I realized that there are three different deploy configurations - referred to as cd-one.yaml, cd-two.yaml, and cd-three.yaml. Ea ...

Once deployed, Google Cloud Function experiences delayed execution

I have implemented a Cloud Function that executes the following steps: retrieving data from an API formatting the retrieved data saving the data in Firestore Here is the code snippet for my implementation: exports.syncItems = functions.https.onRequest((r ...

Loop through an array of strings

When I receive the data as a string[] https://i.sstatic.net/ttyag.png However, when I attempt to loop over it subUrl(arr) { for(let i of arr) { console.log(i); } } No output is being logged. What could be causing this issue? ...