Number values are saved as strings in firestore

泄露秘密 提交于 2020-08-05 06:20:06

问题


I use this function to send 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
                }
            )
        });
});

I have declared some variables as number but when i check the firestore doc, it is saved as strings. please see the screenshot

In the code, i have declared occupationId as a number variable but after it is saved it is a string, again please see the screenshot. Anyone know why it is changing data types?


回答1:


Declarations, e.g.:

const occupationId: number

by themselves do not convert passed data in case if the assignment type is any (it's done so that it was possible to gradually switch from js to ts).

If you need to have a number explicitly - you need to use something that converts the actual value type for you.

One possible way to do that:

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

References:

  • MDN: Number - Convert numeric strings to numbers



回答2:


When you set the value for the object, you have to check whether the value is a valid number or letter, if it's a valid number then you have to convert it to a correct number format else you just need to pass the variable as it is.

+value || value

Example:

const apple = "Apple"
const amount = "5"
const getRealValue = (val) => +val || val

console.log(getRealValue(apple))
console.log(getRealValue(amount))

console.log(typeof getRealValue(apple))
console.log(typeof getRealValue(amount))

In this way you can let the Firestore understand your data type, this process can be done for all of your object variables as iterating through Object.keys



来源:https://stackoverflow.com/questions/48795490/number-values-are-saved-as-strings-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!