如何在Cloud Firestore中对交易执行OR查询?

时间:2019-01-21 10:41:35

标签: javascript google-cloud-firestore

如果myCollection中存在任何单个文档,其中数组包含arr数组的任何值,那么我不想在myCollection2中添加新文档,我想在云函数上运行此查询。

firestore结构

    myCollection
              myDoc1
                  array:[1,2,3]
              myDoc2
              array:[5,8,7]*
   myCollection2 ....

我如何做

const arr=[2,5,8,9];

return db.runTransaction(async t=>{

  for(let i=0,i<arr.length<t++){
    await  t.get(db.collection('myCollection').where('array','array-contains'arr[i]).then(doc=>{
      if(doc.exists) throw new functions.http.httpError('internal','not available');
    })
  }

  return db.collection('mycollection2').add({
    //fields 
  });

});

这是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

没有办法做到。您要做的是将与您的条件相匹配的不同查询组合在一起。这是使用rxjs和Typescript的示例

function getData(value1, value2)
{
    const scenario1 = this.afs.collection(`collection1`, ref => {
                let query: firebase.firestore.CollectionReference | f 
   firebase.firestore.Query = ref;
                query = query.where("field1", "==", value1);
                return query;

            }).snapshotChanges()
                .pipe(take(1))
                .pipe(
                    map(changes => {
                        return changes.map(a => {
                            const data = a.payload.doc.data() as CustomDataType;
                            data.docId = a.payload.doc.id;
                            return data;
                        })
                    })
                );


    const scenario2 = this.afs.collection(`collection1`, ref => {
                let query: firebase.firestore.CollectionReference | firebase.firestore.Query = ref;
                query = query.where("field1", "==", value2);
                return query;

            }).snapshotChanges()
                .pipe(take(1))
                .pipe(
                    map(changes => {
                        return changes.map(a => {
                            const data = a.payload.doc.data() as CustomDataType;
                            data.docId = a.payload.doc.id;
                            return data;
                        })
                    })
                );
            return forkJoin(scenario1,scenario2)
                .pipe(map((arr) => [...arr[0],...arr[1]] ));
}