在firestore查询中实现OR - Firebase firestore

时间:2017-10-30 14:50:56

标签: javascript firebase google-cloud-firestore

我在firestore查询中尝试实现逻辑OR运算符。

db.collection('users').where('company_id', '==', companyId)
                          .where('role', '==', 'Maker')
                          .where('role', '==', 'Checker')
                          .where('role', '==', 'Approver')
                          .get().then(function(adminsSnapshot){


             //Some processing on dataSnapshot
})

但这不是实施OR的正确方法。

我希望所有用户都拥有'Maker,Checker或Approver'的角色。

我如何在firestore查询中实现OR? Doc中没有任何内容。

3 个答案:

答案 0 :(得分:13)

没有" OR"在Cloud Firestore中查询。如果您想在单个查询中实现此目标,则需要使用单个字段maker_or_checker_or_approver: true

当然,您可以随时进行三次查询并在客户端加入。

答案 1 :(得分:1)

现在,通过新增对inarray-contains-any运算符的支持,在Firestore中已使之成为可能。这两个运算符允许在单个查询中查询多达10个值。

https://firebase.googleblog.com/2019/11/cloud-firestore-now-supports-in-queries.html

因此,以您的示例为例,查询看起来像这样。

db.collection('users')
    .where('company_id', '==', companyId)
    .where('role', 'in', ['Maker', 'Checker', 'Approver']);

在上面的示例中,如果您的数据存储在数组中,请用in替换array-contains-any

答案 2 :(得分:0)

您可以使用rxjs组合observable,请参阅下面的angular(6)示例;

orQuery(){

    const $one = this.afs.collection("users", ref => ref.where("company_id","==","companyId")).valueChanges();
    const $two = this.afs.collection("users", ref => ref.where("role","==","Maker")).valueChanges();

    return combineLatest($one,$two).pipe(
        map(([one, two]) => [...one, ...two])
    )
}

getOr(){
    this.orQuery().subscribe(data => console.log(data))
}