从Firestore文档获取字段 [英] Get field from Firestore document
问题描述
是否可以从Firestore对象中提取和解析单个字段,而无需运行For Each或先将其传递给数组?
Is it possible to extract and parse just a single field from a Firestore object without running a For Each or alternatively first passing this to an array?
具体来说,我提取了一个文档,如下所示(工作正常):
Specifically, I have pulled a single document as below (below working):
const docRef = admin
.firestore()
.collection("profiles")
.doc(profileId);
由此,我想解析一个字段(accountBalance),但无法做到这一点(假设可以,但不能):
From this I would like to parse a single field (accountBalance) but not able to do this (assumed to work but does not):
const accountBalance = docRef.accountBalance;
这需要解析吗?
推荐答案
是否可以从Firestore对象中提取和解析单个字段,而无需运行For Each
Is it possible to extract and parse just a single field from a Firestore object without running a For Each
是的,有可能.根据官方文档,您可以使用DocumentSnapshot的 get()函数:
Yes, it is possible. According to the official documentation, you can achieve this using DocumentSnapshot's get() function:
检索fieldPath指定的字段.如果文档或字段不存在,则返回undefined.
Retrieves the field specified by fieldPath. Returns undefined if the document or field doesn't exist.
在代码中,应如下所示:
In code, should look like this:
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("profileId: ", doc.get("profileId"));
} else {
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
这篇关于从Firestore文档获取字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!