Firestore查询中基于动态嵌套属性使用where操作符的实现
Firestore 查询基于变量的嵌套属性
Firestore支持用点符号访问嵌套文档属性,你只需要把动态的语言变量和子属性拼接成完整的路径字符串,就能实现目标查询。
具体实现代码
首先定义你的变量:
const language = "EN"; const targetCategory = "Something";
然后构造查询(推荐用ES6模板字符串,更直观):
// 替换成你的集合名称 db.collection("your-collection") .where(`${language}.category`, "==", targetCategory) .get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${JSON.stringify(doc.data())}`); }); }) .catch((err) => { console.error("查询出错:", err); });
如果你的运行环境不支持ES6模板字符串,也可以用普通字符串拼接:
db.collection("your-collection") .where(language + ".category", "==", targetCategory) .get() // 后续处理逻辑同上
注意事项
只要你的文档结构是类似下面这种嵌套格式,这个查询就能精准匹配对应语言下的category属性:
// 示例文档结构 { "EN": { "category": "Something" }, "FR": { "category": "Quelque chose" } }
内容的提问来源于stack exchange,提问作者David Henry
相关产品推荐
相关产品推荐

