Cease
Cease

Reputation: 1172

iterate over firestore array field with node

I have an array field in a firestore document like so:

enter image description here

Assuming that I have already gotten the DocumentReference which contains this field via:

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

How would I iterate over each string in the array?

Upvotes: 0

Views: 932

Answers (2)

Mr.UV
Mr.UV

Reputation: 100

You can try by first getting reference of a document having all the data and then loop through it. Something like following:

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);
});

Upvotes: -1

Renaud Tarnec
Renaud Tarnec

Reputation: 83103

Do as follows:

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() returns all fields in the document as an Object, and since the field EmergencyContacts is of type Array, you need to loop over the Array.

const emergencyContacts = doc.get("EmergencyContacts"); also works, see the doc.

Upvotes: 3

Related Questions