有没有办法在循环中查询具有多个“where”的 Firestore 集合?

问题描述 投票:0回答:1

我想对文档集合进行查询,每个文档都包含一个数组中的 id。查询应该是动态的,因为数组中的 id 经常变化。我已经尝试过这个但它不起作用

const postsCol = await admin.firestore().collection('posts')
idsList.forEach(elem => {
  postsCol.where('sentBy', '==', elem)
})
postsCol.orderBy("sentAt", "desc").limit(5)
typescript firebase google-cloud-platform google-cloud-firestore
1个回答
3
投票

要查询 Firestore 集合,您需要使用

get()
方法

执行

const postsCol = await admin.firestore().collection('posts')
不会查询数据库,它只是定义一个
CollectionReference
postsCol.where('sentBy', '==', elem)
postsCol.orderBy("sentAt", "desc").limit(5)
相同:它们定义
Query
但不获取数据库。

使用

get()
方法对集合进行的每个查询都是异步操作:
get()
方法返回一个
Promise
,它会解析查询结果。

由于要并行触发多个查询,因此应该使用

Promise.all()
,如下:

const queries = [];

idsList.forEach(elem => {
   queries.push(admin.firestore().collection('posts').where('sentBy', '==', elem).get());
})

Promise.all(queries)
.then(results => {
  //Do whatever you want with the results array which is an array of QuerySnapshots
  //See https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot.html
})

注意:如果您在云函数中使用此代码,请不要忘记返回异步操作返回的Promise(包括

Promise.all()
返回的Promise)。

© www.soinside.com 2019 - 2024. All rights reserved.