Reputation: 1172
I have an array field in a firestore document like so:
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
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
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