Firebase Firestore如何正确实现OR逻辑多ID匹配查询
问题原因
你代码中使用的||是JavaScript原生的逻辑或运算符,只会在代码执行阶段返回sender.id和otherParticipants[0].id中的第一个非空值,最终传给Firestore查询的只有一个ID,因此无法实现两个值的匹配逻辑。
正确实现方案
你要实现同一个字段匹配多个值的OR查询,直接使用Firestore提供的in查询运算符即可,语法为where(字段名, 'in', 候选值数组),会自动匹配字段值等于数组中任意一个元素的文档。
如果后续遇到不同字段的OR匹配需求,再使用Firestore的or过滤器,你当前场景用in更简洁高效。
修正后的代码示例
这里用async/await改写了原有的嵌套回调结构,更易维护:
.then(async () => { console.log('participant', otherParticipants[0].id, sender.id); // 定义要匹配的两个ID数组 const matchIds = [sender.id, otherParticipants[0].id]; try { // 第一次查询:id字段匹配两个ID之一 const idQuerySnapshot = await firebase .firestore() .collectionGroup('favoris') .where('id', 'in', matchIds) .get(); if (idQuerySnapshot.empty) return; // 遍历第一次查询结果(如果需要处理第一次的返回文档可在这里加逻辑) idQuerySnapshot.forEach((doc) => { console.log('data2', doc.data()); }); // 第二次查询:idUser字段匹配两个ID之一 const idUserQuerySnapshot = await firebase .firestore() .collectionGroup('favoris') .where('idUser', 'in', matchIds) .get(); console.log(idUserQuerySnapshot.size); idUserQuerySnapshot.forEach((doc) => { console.log('dataFinal', doc.data()); socialFeedsRef .doc(sender.id) .collection('chat_feed') .doc(channel.id) .set({ favoris: true }, { merge: true }); }); } catch (error) { // 可自行添加错误处理逻辑 console.error('查询出错:', error); } })
注意事项
in查询最多支持传入10个候选值,你当前仅2个符合使用限制- 若执行查询时报缺少索引的错误,直接根据控制台输出的提示到Firebase控制台创建对应索引即可正常使用
内容的提问来源于stack exchange,提问作者Xwingoga06
相关产品推荐
相关产品推荐

