Hank Phung
Hank Phung

Reputation: 2149

Firebase database: how to get first record of each list

I have a nested firebase database with a structure like this:

    posts: {
        0: {
            title: "...",
            content: '...',
            comments: [{
                by: "someone"
            }, {
                by: "anotherone"
            }]
        },
        1: {
          ...
        }
    }

Now I want to get the first comments on each post so I tried

firebase.database().ref('/posts/{postId}/comments/0').once('value',function(snapshot){
   snapshot.forEach(function(child){ console.log(child.val());});
})

But don't know why the only thing I got in the console is false. So are there anyone knows what's wrong or is it impossible to query like that?

Upvotes: 0

Views: 3046

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599686

The Firebase Database SDKs will also read entire nodes. It is not possible to retrieve a subset of a node's data or to get just the keys.

To get the first comment of each post, you must know the key of each post already. Since you can't read just the keys of the posts, this means that you must read all data to get just the first comment of each post:

firebase.database().ref('/posts').once('value',function(snapshot){
  snapshot.forEach(function(child){ 
    console.log(child.val().comments[0]);
  });
})

While this gives the result you need, it is quite wasteful in bandwidth: the client is ready way more data than you need. As usual in NoSQL databases, a better solution may require you to change your data model to fit your use-case. For example: consider storing the latest comment for each post in a separate top-level list:

latest-comments: {
    0: {
        by: "someone"
    },
    1: {
      ...
    }
}

You will need to update this list (in addition to your original comments list) whenever a new comment is posted. But in return, reading the latest comment for each post is now very cheap.

Upvotes: 1

Related Questions