簡體   English   中英

如何從 Firestore 檢索 map 並對其進行迭代?

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

participantUIDs是 Firestore 文檔中的 map:

在此處輸入圖像描述

我從 Firestore 檢索此文檔(這部分成功)並嘗試遍歷 map 以將其鍵作為字符串放入數組中。 不幸的是,它不起作用。 控制台說我不能在participantUIDsMap上使用forEach (也不能使用普通的 for 循環)。 我的 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)
  }
})

chatDoc.get('participantUIDs')不會返回 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. 這就是為什么 forEach 不起作用的原因——在 object 上根本沒有這種方法。 因此,如果您想假設參與者UIDs 是 Firebase map 字段,您的分配應該看起來更像這樣:

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

如果要迭代 object 的屬性,可以使用 JavaScript 提供的眾多選項之一。 請參閱: 遍歷 object 屬性

是的,您在這里“丟失”了類型信息,是的,如果您不能安全地進行類型假設,您可能應該對所有內容進行更多的手動類型檢查。 Firestore SDK 根本沒有為您提供這些,因為文檔沒有強制它們的架構。

我知道這是舊的,但我遇到了同樣的問題並且能夠解決:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM