javascript - Firebase:返回数组中具有 id 的所有集合项,以便执行 `onSnapshot`

标签 javascript firebase firebase-realtime-database

这应该是一个简单的查询,但我似乎无法让它工作或找到如何完成它。

我有一个数组中某个集合的可接受 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.allacceptableIds 上做一个映射来获取它们,但对于这种特殊情况,我还需要设置 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/

相关文章:

javascript - 为每一行发送 AJAX

javascript - Web动画API回调函数

javascript - Windows Phone 上的 Firebase 存储上传失败并出现未知错误

android - 依赖项有什么问题?我正在使用 androidX

java - 如何从 Firebase 获取特定的子值?

javascript - 不和谐机器人 : struggling to tally emoji reacts for voting

javascript - Drupal - 使用框架显示自定义 php/javascript?

javascript - 如何为网络上的多个页面维护 Firebase Auth?

android - 无法在 Android studio 中构建 firebase gradle

javascript - Firebase 安全规则 : restrict write only to this uid,,几个字段除外