如何在Firestore数据库中查询数组内匹配指定id的文档?
Firestore 查询对象数组内字段返回空的解决方案
错误原因
你当前使用的where('participants.id', '==', otherUserID)语法仅适用于participants为单个嵌套对象的场景,当participants是对象数组时,Firestore 原生不支持直接对数组内部的对象字段做等值匹配,因此会返回0条结果。
可行解决方案
方案1:使用array-contains匹配完整对象
如果你的查询逻辑可以拿到数组内存储的完整用户对象(和数据库中存储的字段完全一致,无缺失、无多余字段),可以直接匹配整个对象:
const deleteAbuse = (type) => { const participants = channel?.otherParticipants; if (!participants || participants.length != 1) { return; } const myID = currentUser.id; const targetParticipant = participants[0]; channelDB // 直接匹配整个participant对象,字段要和数据库存储完全一致 .where('participants', 'array-contains', targetParticipant) .get() .then((querySnapshot) => { console.log(querySnapshot.size); querySnapshot.forEach((doc) => { console.log(doc.ref); //doc.ref.delete(); }); }); };
方案2:新增冗余ID数组查询(官方推荐)
这是Firestore处理数组内字段查询的通用最佳实践,你只需要在数据写入时额外新增一个participantIds字段,类型为字符串数组,存储所有参与人的id,后续查询直接操作这个字段即可:
- 写入数据时同步更新:
// 示例写入逻辑,新增participantIds字段 await channelDB.add({ participants: [user1, user2], participantIds: [user1.id, user2.id], // 其他字段... })
- 修改查询代码:
const deleteAbuse = (type) => { const participants = channel?.otherParticipants; if (!participants || participants.length != 1) { return; } const myID = currentUser.id; const otherUserID = participants[0].id; channelDB .where('participantIds', 'array-contains', otherUserID) // 如果需要同时匹配两个用户的会话,可以用array-contains-all // .where('participantIds', 'array-contains-all', [myID, otherUserID]) .get() .then((querySnapshot) => { console.log(querySnapshot.size); querySnapshot.forEach((doc) => { console.log(doc.ref); //doc.ref.delete(); }); }); };
内容的提问来源于stack exchange,提问作者Xwingoga06
相关产品推荐
相关产品推荐

