How to get size of an element/list in Firebase wit

2019-01-06 21:17发布

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

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

ps Javascript SDK

2条回答
时光不老,我们不散
2楼-- · 2019-01-06 21:19

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

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=true parameter, 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?

查看更多
仙女界的扛把子
3楼-- · 2019-01-06 21:42

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

Object.keys(users).length;

Post: Length of a JavaScript object

查看更多
登录 后发表回答