如何获取Firestore文档中的字段? [英] How to get fields in a firestore document?
问题描述
我正在使用与Firestore配合使用的某些Cloud函数.我正在尝试获取特定文档的字段列表.例如,我有一个来自even.data.ref
的文档参考,但是我不确定该文档是否包含我正在查看的字段.我想获取字段名称的列表,但是我不确定该怎么做.
我试图使用Object.keys()
方法来获取数据键的列表,但是我只得到数字列表(0,1 ...),而不是字段名称.
我尝试使用documentSnapShot.contains()
方法,但似乎不起作用.
I am working on some Cloud functions that works with Firestore. I am trying to get a list of fields of a specific document. For example, I have a document reference from the even.data.ref
, but I am not sure if the document contains the field I am looking at. I want to get a list of the fields' name, but I am not sure how to do it.
I was trying to use Object.keys()
method to get a list of keys of the data, but I only get a list of number (0, 1...), instead of name of fields.
I tried to use the documentSnapShot.contains()
method, but it seems doesn't work.
exports.tryHasChild=functions.firestore.document('cities/{newCityId}')
.onWrite((event) =>{
if (event.data.exists) {
let myRef = event.data.ref;
myRef.get().then(docSnapShot => {
if (docSnapShot.contains('population')) {
console.log("The edited document has a field of population");
}
});
推荐答案
作为文档将Cloud Firestore触发器用于Cloud Functions 显示后,您可以使用event.data.data()
获取文档的数据.
As the documentation on using Cloud Firestore triggers for Cloud Functions shows, you get the data of the document with event.data.data()
.
然后,您可以使用JavaScript的Object.keys()
方法遍历字段名称,或通过简单的数组检查来测试数据是否包含字段:
Then you can iterate over the field names with JavaScript's Object.keys()
method or test if the data has a field with a simple array check:
exports.tryHasChild=functions.firestore.document('cities/{newCityId}')
.onWrite((event) =>{
if (event.data.exists) {
let data = event.data.data();
Object.keys(data).forEach((name) => {
console.log(name, data[name]);
});
if (data["population"]) {
console.log("The edited document has a field of population");
}
});
这篇关于如何获取Firestore文档中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!