【问题标题】:iterate over firestore array field with node使用节点迭代 firestore 数组字段
【发布时间】:2021-02-27 16:59:23
【问题描述】:

我在 Firestore 文档中有一个数组字段,如下所示:

假设我已经通过以下方式获得了包含此字段的 DocumentReference:

var myref = db.collection("foo").doc("bar");

如何遍历数组中的每个字符串?

【问题讨论】:

  • 你应该提供一个清晰的场景和你面临的问题,以及你到底想做什么。

标签: javascript node.js firebase google-cloud-firestore


【解决方案1】:

如下操作:

var docRef = db.collection("foo").doc("bar");

docRef.get().then((doc) => {
    if (doc.exists) {
        const emergencyContacts = doc.data().EmergencyContacts;
        for (var key in emergencyContacts) {
          console.log(emergencyContacts[key]);
        }
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch((error) => {
    console.log("Error getting document:", error);
});

doc.data() 将文档中的所有字段作为对象返回,并且由于字段EmergencyContacts 的类型为Array,因此您需要遍历数组。

const emergencyContacts = doc.get("EmergencyContacts"); 也可以使用,请参阅doc

【讨论】:

    【解决方案2】:

    您可以尝试首先获取包含所有数据的文档的引用,然后循环遍历它。 类似于以下内容:

    var docRef = db.collection("cities").doc("SF");
    
    docRef.get().then((doc) => {
        if (doc.exists) {
            doc.data().EmergencyContacts.forEach(data => console.log("data", data));
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    }).catch((error) => {
        console.log("Error getting document:", error);
    });
    

    【讨论】:

    • 在这种情况下 doc.data() 不返回文档的全部内容吗?我不想循环遍历文档,我想遍历文档中某个字段的内容
    • 是的,我认为您只需要先获取数据即可对其进行迭代。我在我的项目中遇到了同样的情况,这种方法效果很好。 @停止了解更多信息:firebase.google.com/docs/firestore/query-data/get-data
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 2020-01-18
    • 2011-06-01
    • 2012-12-17
    • 2021-12-21
    相关资源
    最近更新 更多