如何在用typescript编写的谷歌云函数中检索和使用firebase数据



问题

我在Firebase上存储了一个文档,其结构如下所示。

通过使用typescript编写的Google Cloud函数,我想访问并使用存储在Firebase项目中的JSON数据。我不确定该用什么语法。

Firebase文档结构:

"users": {
"tim": {
"score": 1200
"health": 200
"items": {
123123,
182281,
123344,
}
}
"james": {
"score": 100
"health": 50
"items": {
143553,
567454,
}
}
}

我目前使用以下代码从Firebase检索数据。

import * as admin from "firebase-admin";
export class ScoreHandler {
constructor(private firestore: FirebaseFirestore.Firestore) {}
async calculateFinalScore(name: string): Promise<number> {
try{
const document = await this.firestore
.collection("users")
.doc("users")
.get();

// Check if record exists
if (document.data() === undefined) {
throw console.warn("unable to find users document data);
}

//!!THIS IS WRONG!! not sure how to read in and access this data?
const score: number = document.data()["users"]["tim"]["score"];
const health: number = document.data()["users"]["tim"]["health"];
const items: Array<number> = document.data()["users"]["tim"]["items"];
//Calculate Final score using score, health and items
const finalScore: number = score * health * items.length;
return finalScore;

} catch (e) {
// Log the Error on the Console
console.error(e);
return 0.0;
}

}

我不确定从Typescript中的文档快照访问数据的正确语法。我希望能够将我的firebase项目中的分数、健康状况和项目数组输入到我的云函数类中。

非常感谢您的帮助
谢谢!

我试图获取数据,但不断获取对象可能是未定义的错误,无法实际获取数据。

要访问数据,可以在快照对象上使用data()方法。此方法将文档中的数据作为对象返回。

您使用data()方法获取文档快照中的数据,但没有使用正确的属性名称来访问数据。data()方法返回一个对象,而不是JSON对象。因此,您需要为对象使用正确的属性名称。

尝试访问tim对象的score属性,如下所示:

const score: number = document.data()["users"]["tim"]["score"];

访问data()方法返回的JavaScript对象中score属性的正确方法如下:

const score: number = document.data()["tim"]["score"];

要访问tim对象中的其他属性,可以使用以下语法:

const health: number = document.data()["tim"]["health"];
const items: Array<number> = document.data()["tim"]["items"];

以下是使用正确语法访问Firestore文档快照中的数据的calculateFinalScore()方法的样子:

async calculateFinalScore(name: string): Promise<number> {
try{
const document = await this.firestore
.collection("users")
.doc("users")
.get();
// Check if record exists
if (document.data() === undefined) {
throw console.warn("unable to find users document data");
}
// Get the score, health and items from the document snapshot
const score: number = document.data()["tim"]["score"];
const health: number = document.data()["tim"]["health"];
const items: Array<number> = document.data()["tim"]["items"];
// Calculate Final score using score, health and items
const finalScore: number = score * health * items.length;
return finalScore;
} catch (e) {
// Log the Error on the Console
console.error(e);
return 0.0;
}
}

用户的名称被硬编码为";tim";。如果您想为不同的用户访问数据,则需要将"替换为";tim";属性名称与要访问的用户的名称。类似:

const score: number = document.data()["james"]["score"];
const health: number = document.data()["james"]["health"];
const items: Array<number> = document.data()["james"]["items"];

最新更新