我想对文档集合进行查询,每个文档都包含一个数组中的 id。查询应该是动态的,因为数组中的 id 经常变化。我已经尝试过这个但它不起作用
const postsCol = await admin.firestore().collection('posts')
idsList.forEach(elem => {
postsCol.where('sentBy', '==', elem)
})
postsCol.orderBy("sentAt", "desc").limit(5)
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)。