【问题标题】:Query firebase nodes to get counts with dynamic paths查询 firebase 节点以获取动态路径的计数
【发布时间】:2019-11-28 16:46:48
【问题描述】:

我正在尝试找出一种更优雅的方式来做到这一点......

我正在存储消息对象并希望获取包含新消息的对话总数。我的节点结构是这样的:

/messages/{userId}/{receipientId}/{messageId}/{message: '', senderId: '', status: 'new|read' }

*** messageId 是从 firebase 自动生成的密钥。 userId 和receipientId 是来自auth 的ID。

我为获得徽章中的数字而编写的第一个代码是这样的:

firebase.database().ref()
  .child(`/messages/${userId}/${receipientId}`)
  .orderByChild('status')
  .equalTo('new')
  .once('value')
  .then(innerSnapshot => {
    if (innerSnapshot.val() !== null) {
      if (newConversations.findIndex(item => item === entry) === -1) {
        newConversations.push(entry);
      }
    } 
  })
  .catch();

这需要我将其包装在另一个查询中,以在为找到的每个项目运行单独的查询之前获取所有接收者 ID。它可以工作...但是非常暴力。

基本上,我只需要知道在其下方某处具有“status: 'new'”条目的receipientId 节点的数量。

【问题讨论】:

    标签: reactjs typescript firebase firebase-realtime-database


    【解决方案1】:

    您正尝试在 JSON 中跨多个动态级别进行查询,而实时数据库无法做到这一点。见Firebase Query Double NestedFirebase query if child of child contains a value

    与 NoSQL 数据库一样,请考虑修改/增强您的数据结构以允许您想要的用例。因此,如果您想知道拥有status: 'new' 的收件人数量,请考虑精确存储:消息收件人的顶级列表及其消息状态。这几乎就是你现在所拥有的逆数据结构,这就是为什么它有点像倒排索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2021-01-15
      • 2012-05-15
      相关资源
      最近更新 更多