Javascript 如何在不获取全部信息的情况下获取 Firebase 中元素/列表的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38443421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:29:33  来源:igfitidea点击:

How to get size of an element/list in Firebase without get it all?

javascriptfirebasefirebase-realtime-database

提问by Rodolfo Paranhos

I need to measure the size/length of an element or list in Firebase but I don't need the real content.

我需要在 Firebase 中测量元素或列表的大小/长度,但我不需要真正的内容。

Something like firebase.database().ref("users/").once("length" || "size").then(callback)

就像是 firebase.database().ref("users/").once("length" || "size").then(callback)

psJavascript SDK

psJavascript SDK

回答by Frank van Puffelen

Firebase doesn't have a count operator, so the only way is to download all children orkeep a separate <children>_countproperty in sync. The latter is not a trivial task (see my answer here for one approachand this example Cloud Function), so most often developers likely end up going with the downloads-too-much-data-but-is-trivial approach:

Firebase 没有计数运算符,因此唯一的方法是下载所有子项保持单独的<children>_count属性同步。后者不是一项微不足道的任务(请参阅我在此处的答案以了解一种方法和此示例 Cloud Function),因此大多数情况下,开发人员最终可能会采用下载过多数据但很简单的方法:

ref.child("messages").on("value", function(snapshot) {
  console.log("There are "+snapshot.numChildren()+" messages");
})

A more efficient way to count the children would be to fire a REST call with shallow=trueparameter, which will give you just the keys. See In Firebase, is there a way to get the number of children of a node without loading all the node data?

计算子项的更有效方法是使用shallow=true参数触发 REST 调用,这将只为您提供密钥。请参阅在 Firebase 中,有没有办法在不加载所有节点数据的情况下获取节点的子节点数?

回答by Aleks Witko

Also found a post which does it a different way...

还发现了一个帖子,它以不同的方式...

Object.keys(users).length;

Post: Length of a JavaScript object

Post:JavaScript 对象的长度