如何在Firestore中查询包含指定member_id的members子映射文档
Firestore查询:获取包含指定成员的聊天室文档
现有数据结构
chatRoom: { MVyMPi78DOwVQ5w5GnYe: { ... members: { <member_1_id>: { id: xxxxx, unreadmessagecount: xx }, <member_2_id>: { id: xxxxx, unreadmessagecount: xx } }, La234Pi78DOwVQ5w5GnYe: { ... members: { <member_1_id>: { id: xxxxx, unreadmessagecount: xx }, <member_2_id>: { id: xxxxx, unreadmessagecount: xx } } } }
查询实现
针对这种嵌套映射结构,Firestore支持通过exists操作符检查指定成员ID对应的路径是否存在,以此筛选出包含该成员的聊天室文档。
1. Firestore Web v9(模块化API)
import { collection, query, where, getDocs } from "firebase/firestore"; import { db } from "./firebase-config"; // 替换为你的Firestore实例 const targetMemberId = "你的目标成员ID"; // 构建查询 const chatRoomsQuery = query( collection(db, "chatRoom"), where(`members.${targetMemberId}`, "exists", true) ); // 执行查询并获取结果 async function getChatRoomsForMember() { const querySnapshot = await getDocs(chatRoomsQuery); const chatRooms = []; querySnapshot.forEach((doc) => { chatRooms.push({ id: doc.id, ...doc.data() }); }); console.log("包含指定成员的聊天室:", chatRooms); return chatRooms; } // 调用函数 getChatRoomsForMember();
2. Firestore Web v8(命名空间API)
const db = firebase.firestore(); // 替换为你的Firestore实例 const targetMemberId = "你的目标成员ID"; // 构建并执行查询 db.collection("chatRoom") .where(`members.${targetMemberId}`, "exists", true) .get() .then((querySnapshot) => { const chatRooms = []; querySnapshot.forEach((doc) => { chatRooms.push({ id: doc.id, ...doc.data() }); }); console.log("包含指定成员的聊天室:", chatRooms); }) .catch((error) => { console.error("查询出错:", error); });
说明
- 使用
where(members.${targetMemberId}, "exists", true)可以精准匹配到members映射中包含该成员ID的文档 - 注意替换代码中的
targetMemberId为实际要查询的成员ID,以及确保Firestore实例配置正确
内容的提问来源于stack exchange,提问作者Mohammad Danish
相关产品推荐
相关产品推荐

