Firebase与Flutter:如何返回集合Map中标记为true的字符串
从Firebase集合的Map中筛选标记为true的字符串
由于Firestore无法直接通过查询筛选Map中所有值为true的键,需要先获取文档数据,再在客户端进行处理,下面以Web端JavaScript SDK为例给出实现方案:
单文档筛选
如果只需要处理单个文档,代码如下:
// 导入Firebase相关模块 import { doc, getDoc } from "firebase/firestore"; import { db } from "./firebase-config"; // 替换为你的Firebase配置文件 async function getSelectedKeys() { // 替换为你的集合名称和目标文档ID const targetDoc = doc(db, "你的集合名", "目标文档ID"); const docSnapshot = await getDoc(targetDoc); if (docSnapshot.exists()) { const docData = docSnapshot.data(); // 替换为你的Map类型字段名 const targetMap = docData.你的Map字段名; // 筛选出值为true的键 const trueKeys = Object.entries(targetMap) .filter(([key, value]) => value === true) .map(([key]) => key); console.log("筛选结果:", trueKeys); return trueKeys; } else { console.log("目标文档不存在"); } } // 调用函数执行筛选 getSelectedKeys();
整个集合批量筛选
如果需要遍历集合中所有文档,批量筛选每个文档Map里的true值键,代码如下:
import { collection, getDocs } from "firebase/firestore"; import { db } from "./firebase-config"; async function getAllSelectedKeys() { // 替换为你的集合名称 const collectionRef = collection(db, "你的集合名"); const querySnapshot = await getDocs(collectionRef); const allTrueKeys = []; querySnapshot.forEach((doc) => { const docData = doc.data(); const targetMap = docData.你的Map字段名; if (targetMap) { const trueKeys = Object.entries(targetMap) .filter(([key, value]) => value === true) .map(([key]) => key); allTrueKeys.push(...trueKeys); } }); console.log("全集合筛选结果:", allTrueKeys); return allTrueKeys; } getAllSelectedKeys();
关键注意点
- 确保Firebase安全规则配置正确,允许读取目标集合/文档
- 代码中的
你的集合名、目标文档ID、你的Map字段名需要替换为你实际的Firestore结构信息 - 其他平台(Android/iOS)逻辑一致:先获取文档数据,遍历Map键值对,筛选值为true的键即可
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

