Florian Walther
Florian Walther

Reputation: 6961

How can I retrieve a map from Firestore and iterate over it?

participantUIDs is a map in a Firestore document:

enter image description here

I retrieve this document from Firestore (this part is successful) and try to iterate over the map to put its keys as strings into an array. Unfortunately, it doesn't work. The console is saying that I can't use forEach (and neither a normal for-loop) on participantUIDsMap. What's wrong with my Map?

const chatDoc = await admin.firestore().doc(`group_chats/${context.params.chatId}`).get()
// the document is retrieved successfully, I checked it with another field.
const participantUIDsMap: Map<string, boolean> = chatDoc.get('participantUIDs')
const participantUIDsArray: string[] = []
participantUIDsMap.forEach((value, key) => {
  if (value === true && key != senderUid) {
    participantUIDsArray.push(key)
  }
})

Upvotes: 2

Views: 1790

Answers (2)

BGMX
BGMX

Reputation: 25

I know this is old but I ran into this same problem and was able to solve as:

const docRef = doc(db, "collection", "id");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
    console.log("Document data:", docSnap.data());
    console.log("Map field:", docSnap.data().mapField)
    docSnap.data().mapField.forEach((value, key) => {
        console.log('Value', value, 'key', key)
    })
} else {
    // doc.data() will be undefined in this case
    console.log("No such document!");
}    

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317477

chatDoc.get('participantUIDs') will not return an ES6 Map object. If the named field is a map type field, it returns a plain JavaScript object whose property names are the same names as the fields in the Firestore map field. That's why forEach won't work - there is simply no such method on that object. So, if you want to make the assumption that participantUIDs is a Firebase map field, your assignment should look more like this:

const participantUIDs: any = chatDoc.get('participantUIDs')

If you want to iterate the properties of that object, you can use one of the many options JavaScript provides. See: Iterate through object properties

Yes, you are "losing" type information here, and yes, you should probably do more manual type checking on everything, if you can't make type assumptions safely. The Firestore SDK simply does not provide that for you, since documents have no schema enforced upon them.

Upvotes: 3

Related Questions