仅读取 firebase 中的某些字段 [英] read only certain fields in firebase

查看:25
本文介绍了仅读取 firebase 中的某些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像

users: {
  user1: { 
    name:'qwert', 
    id: 123,
    num: 9999 
  },
  user2: { 
    name:'zxcvb', 
    id: 456,
    num: 8888 
  }
}

如何只读取所有用户的名字?

How can I read only name of all the users?

我的预期结果:

{
  user1:{
    name:'qwert'
  }, 
  user2:{
    name:'zxcvb'
  }
}

如果我在 JavaScript 中使用它:

If I use this in JavaScript:

ref('users').once('value').then((snap)=>{console.log(snap.val())})

我得到所有用户的所有数据(但我只想要每个人的名字)

I get all the users with that all their data (but I only want name of each)

我应该在查询中进行哪些更改才能获得预期结果?

What changes should I make in my query to get the expected result?

任何建议都将受到高度赞赏并且非常有帮助.我尝试搜索文档,但没有得到我想要查找的内容.

Any suggestions would be highly appreciated and really helpful. I tried searching through the docs but didn't get what I was trying to look for.

我的最终目标是降低读取不必要数据的成本.

My ultimate aim is to cut down the costs of reading unnecessary data.

推荐答案

无法仅从当前数据模型中选择名称,Firebase 始终检索完整节点.因此,您要么必须按照 Peter 的回答进行操作,读取所有数据但提取客户端的用户名,要么必须修改数据模型以允许用例.

There is no way to select only the names from your current data model, Firebase always retrieves full nodes. So you will either have to do what Peter answered, reading all data but extracting the user name client side, or you will have to modify you data model to allow the use-case.

后者很简单.如果你想加载一个用户名列表,你应该在数据库中存储一个用户名列表:

The latter is quite simple. If you want to load a list of user names, you should store a list of user names in the database:

users: {
  user1: { 
    name:'qwert', 
    id: 123,
    num: 9999 
  },
  user2: { 
    name:'zxcvb', 
    id: 456,
    num: 8888 
  }
},
usernames: {
  user1: 'qwert', 
  user2: 'zxcvb'
}

使用这种结构,只需读取名称即可.

With this structure, it is trivial to read only the names.

另见:

  • Fetch particular fields from Firebase database
  • How to pull the data partially from firebase database
  • More efficient way to retrieve Firebase Data? (a more complex scenario of nesting data)

这篇关于仅读取 firebase 中的某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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