Firestore:如何根据对象属性查询含指定邮箱的联系人文档
检索包含特定邮箱的Firestore文档
要解决你的问题,首先得明确你的数据结构:emails是一个嵌套对象,邮箱地址是这个对象的键,对应的值是包含name和text的子对象。你之前的代码用== true无法匹配,因为目标路径对应的是一个对象而非布尔值,所以永远找不到结果。
下面是两种可行的正确查询方式:
方法1:检查邮箱路径是否存在(推荐)
使用Firestore的exists操作符,直接判断指定的邮箱键是否存在于emails对象中:
const targetEmail = 'susan@xpto.com'; firebase.firestore().collection('contacts') .where(new firebase.firestore.FieldPath('emails', targetEmail), 'exists', true) .get() .then(querySnapshot => { if (querySnapshot.empty) { console.log('未找到包含该邮箱的联系人文档'); return; } // 遍历匹配到的文档 querySnapshot.forEach(doc => { console.log(`找到文档ID: ${doc.id},数据:`, doc.data()); }); }) .catch(error => { console.error('查询过程中出错:', error); });
方法2:检查邮箱路径的值非空
如果你的Firestore版本不支持exists操作符(较旧版本),可以通过判断目标路径的值不等于null来实现(因为存在的邮箱键对应的值是一个非空对象):
const targetEmail = 'susan@xpto.com'; firebase.firestore().collection('contacts') .where(new firebase.firestore.FieldPath('emails', targetEmail), '!=', null) .get() .then(querySnapshot => { // 处理结果逻辑和方法1一致 if (querySnapshot.empty) { console.log('未找到包含该邮箱的联系人文档'); return; } querySnapshot.forEach(doc => { console.log(`找到文档ID: ${doc.id},数据:`, doc.data()); }); }) .catch(error => { console.error('查询过程中出错:', error); });
额外扩展:如果需要匹配邮箱对应的属性
如果你不仅要检查邮箱存在,还要匹配该邮箱对应的text或name属性,比如找Susan是manager的文档,可以这样写:
const targetEmail = 'susan@xpto.com'; firebase.firestore().collection('contacts') .where(new firebase.firestore.FieldPath('emails', targetEmail, 'text'), '==', 'manager') .get() .then(querySnapshot => { // 处理结果 });
内容的提问来源于stack exchange,提问作者InfoStatus
相关产品推荐
相关产品推荐

