简体   繁体   English

从google firebase实时数据库web获取数据

[英]Get data from google firebase realtime database web

Question: how can I take only the week numbers (without information what is inside each week)?问题:我怎样才能只取周数(没有信息每周里面有什么)?

实时数据库

I did like this, but I also get what's inside every week.我确实喜欢这个,但我每周也会得到里面的东西。 I only need week numbers:我只需要周数:

const db = firebase.database();
const weeksRef = db.ref('MyApp/Weeks');
weeksRef.on('value', items =>{
    return items.val()
})

Firebase always loads complete nodes from the Realtime Database. Firebase 总是从实时数据库加载完整的节点。 There is no way to get the keys from your JSON, without also getting their values.没有办法从您的 JSON 中获取密钥,而不获取它们的值。

The closest you can get with your current data structure is to only use the keys of the JSON:与当前数据结构最接近的是仅使用JSON 的键:

const db = firebase.database();
const weeksRef = db.ref('MyApp/Weeks');
weeksRef.on('value', items =>{
  items.forEach((child) => {
    console.log(child.key);
  })
})

The above will print only the keys, but it is still downloading all data under each key too.以上将仅打印密钥,但它仍在下载每个密钥下的所有数据。 To prevent that, you will need to modify your data structure to allow the use-case, for example by adding a node that keeps only the week numbers :为防止这种情况,您需要修改数据结构以允许用例,例如通过添加仅保留周的节点:

WeekNumbers: {
  "1": true,
  "2": true,
  "3": true,
  "4": true,
  "5": true,
  "6": true
}

The true values here are needed, since Firebase won't store a key unless there is a value under it.这里需要true的值,因为 Firebase 不会存储键,除非它下面有一个值。

With the above structure you can get the same output as before with:使用上述结构,您可以获得与以前相同的 output :

const db = firebase.database();
const weeksRef = db.ref('MyApp/WeekNumbers');
weeksRef.on('value', items =>{
  items.forEach((child) => {
    console.log(child.key);
  })
})

As you can see, the code remains almost the same, but a lot less data is being downloaded.如您所见,代码几乎保持不变,但下载的数据要少得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM