繁体   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