read only certain fields in firebase

前端 未结 2 1150
予麋鹿
予麋鹿 2020-12-11 10:00

If I have a database like

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


        
相关标签:
2条回答
  • 2020-12-11 10:45

    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.

    Also see:

    • 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)
    0 讨论(0)
  • 2020-12-11 10:53

    To retrieve only the names of the users, then try the following:

    firebase.database().ref().child("users").on("value", function (snapshot) {
      snapshot.forEach(function(childSnapshot) {
       var name=childSnapshot.val().name;
      });
    });
    

    Here the snapshot is users, then you iterate inside user1 and user2 to be able to access the names of these users and retrieve them.

    0 讨论(0)
提交回复
热议问题