在Firebase中,有没有办法获取节点的子节点数而不加载所有节点数据? [英] In Firebase, is there a way to get the number of children of a node without loading all the node data?

查看:512
本文介绍了在Firebase中,有没有办法获取节点的子节点数而不加载所有节点数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以通过

firebase_node.once('value', function(snapshot) { alert('Count: ' + snapshot.numChildren()); });

但我相信这会从服务器获取该节点的整个子树。对于巨大的列表,这似乎RAM和延迟密集。有没有办法获取计数(和/或一个子名字的列表)而不提取整个事情?

But I believe this fetches the entire sub-tree of that node from the server. For huge lists, that seems RAM and latency intensive. Is there a way of getting the count (and/or a list of child names) without fetching the whole thing?

推荐答案

您提供的代码段确实加载了整组数据,然后在客户端计数,这对于大量数据来说可能非常慢。

The code snippet you gave does indeed load the entire set of data and then counts it client-side, which can be very slow for large amounts of data.

Firebase不目前有一种方法来计算孩子没有加载数据,但我们计划添加它。

Firebase doesn't currently have a way to count children without loading data, but we do plan to add it.

现在,一个解决方案是保持一个计数器的孩子数并在每次添加新孩子时更新它。您可以使用事务对项目进行计数,例如在此代码中跟踪upvodes:

For now, one solution would be to maintain a counter of the number of children and update it every time you add a new child. You could use a transaction to count items, like in this code tracking upvodes:

var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
  return (current_value || 0) + 1;
});

有关详情,请参阅 https://www.firebase.com/docs/transactions.html

更新:
Firebase最近发布的Cloud Functions。使用云功能,您不需要创建自己的服务器。你可以简单地编写JavaScript函数并将其上传到Firebase。

UPDATE: Firebase recently released Cloud Functions. With Cloud Functions, you don't need to create your own Server. You can simply write JavaScript functions and upload it to Firebase. Firebase will be responsible for triggering functions whenever an event occurs.

例如,如果你想计算upvotes,你应该创建一个类似于这个结构的结构:

If you want to count upvotes for example, you should create a structure similar to this one:

{
  "posts" : {
    "-JRHTHaIs-jNPLXOQivY" : {
      "upvotes_count":5,
      "upvotes" : {
      "userX" : true,
      "userY" : true,
      "userZ" : true,
      ...
    }
    }
  }
}

当向 upvotes 节点进行新写入时,会增加 upvotes_count 的javascript函数。

And then write a javascript function to increase the upvotes_count when there is a new write to the upvotes node.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.countlikes = functions.database.ref('/posts/$postid/upvotes').onWrite(event => {
  return event.data.ref.parent().child('upvotes_count').set(event.data.numChildren());
});

您可以阅读文档,以了解如何获取开始使用云功能

You can read the Documentation to know how to Get Started with Cloud Functions.

这篇关于在Firebase中,有没有办法获取节点的子节点数而不加载所有节点数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆