[英]Firebase query with multiple combined WHERE conditions ie where (condition1) OR where(condition2)
我希望在查询一些 firebase collections 时结合多个 where 条件。 以下是有效的,但想进一步扩展它。
const db = admin.firestore();
const snapshot = await db.collection(collectionId).where("published", "!=", false).get();
以上工作,但想添加另一个 OR where("another_property", ",=", "some_value") 来实现我需要的。 但无法获得正确的语法。
在 NoSQL 数据库中,您应该围绕将要进行的查询构建数据,而不是围绕数据扭曲查询。
让我们先看看 go 老派,看看你的查询的真值表:
一个 | 乙 | 一个' | 乙' | A' 或 B' |
---|---|---|---|---|
0 | 0 | 1 | 1 | 1 |
1 | 0 | 0 | 1 | 1 |
0 | 1 | 1 | 0 | 1 |
1 | 1 | 0 | 0 | 0 |
因此,在您查询的数据中,如果published
和another_value
都与您要否定的值匹配,则将它们从结果中排除。
这导致了最简单的可用方法 - 将两者的值连接到一个新字段中 - 然后将其作为否定添加到您的查询中。
"/somedoc": {
"published": false,
"another_property": "some_value",
"published_another_property": "false_some_value"
}
然后查询您要查找的结果:
const snapshot = await db.collection(collectionId)
.where("published_another_property", "!=", [false, "some_value"].join("_"))
.get();
使用模块化 SDK,您可以创建自己的 QueryConstraint 构建器:
const whereNotAll = (fieldMap) => {
const keys = Object.keys(fieldMap).sort(); // note: keys are now in lexicographic order
// so for the above fields, it'd need "another_property_published" instead
const values = keys.map(key => fieldMap[key]);
return where(keys.join("_"), "!=", values.join("_"))
}
const constraint = whereNot({ "published": false, "another_property": "some_value" });
// equivalent of where("another_property_published", "!=", "some_value_false");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.