这应该是一个简单的查询,但我似乎无法让它工作或找到如何完成它。
我有一个数组中某个集合的可接受 ID 列表。我想要get
该集合中与这些 id 之一匹配的每一项。有点像常用的 array-contains 的反面。例如:
const acceptableIds = ['id1', 'id2', 'id3']
const myCollectionDispose = await db
.collection('myCollection')
.where('id', 'is-in-array', acceptableIds)
.onSnapshot(doSomething)
我知道我可以用 Promise.all
在 acceptableIds
上做一个映射来获取它们,但对于这种特殊情况,我还需要设置 onSnapshot
在它的末尾(如示例代码中所示),所以这是行不通的。
无论如何,最好的方法是什么?
可以使用 where 通过 id 获取 myCollection
的项目,也可以在 生成的数组上设置
。以防万一后一个相关,这里是代码:onSnapshot
Promise.all
const acceptableIds = ['id1', 'id2', 'id3']
const myCollectionDispose = await Promise.all(
acceptableIds.map(id => {
return db
.collection('myCollection')
.doc(id)
.onSnapshot(doSomething)
})
)
谢谢!
最佳答案
您可以将每个 Promise 保存在一个数组中,然后在每个 Promise 完成时使用 Promise.all()。
const acceptableIds = ['id1', 'id2', 'id3']
const promises = []
for (var i = 0; i < acceptableIds.length; i++) {
promises.push(
db.collection('myCollection')
.where('id', 'array-contains', acceptableIds[i])
.onSnapshot( /* Do Something */ )
)
}
Promise.all(promises).then(() => {
// Whatever you need to do next with all the snapshots (e.x. remove them all)
})
关于javascript - Firebase:返回数组中具有 id 的所有集合项,以便执行 `onSnapshot`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57014145/