4

From the Transactions doc, second paragraph:

The intention here is for the client to increment the total number of chat messages sent (ignore for a moment that there are better ways of implementing this).

What are some standard "better ways" of implementing this?

Specifically, I'm looking at trying to do things like retrieve the most recent 50 records. This requires that I start from the end of the list, so I need a way to determine what the last record is.

The options as I see them:

  • use a transaction to update a counter each time a record is added, use the counter value with setPriority() for ordering
  • forEach() the parent and read all records, do my own sorting/filtering at client
  • write server code to analyze Firebase tables and create indexed lists like "mostRecent Messages" and "totalNumberOfMessages"

Am I missing obvious choices?

Kato
  • 40,352
  • 6
  • 119
  • 149

1 Answers1

5

To view the last 50 records in a list, simply call "limit()" as shown:

var data = new Firebase(...);
data.limit(50).on(...);

Firebase elements are ordering first by priority, and if priorities match (or none is set), lexigraphically by name. The push() command automatically creates elements that are ordered chronologically, so if you're using push(), then no additional work is needed to use limit().

To count the elements in a list, I would suggest adding a "value" callback and then iterating through the snapshot (or doing the transaction approach we mention). The note in the documentation actually refers to some upcoming features we haven't released yet which will allow you to count elements without loading them first.

bennlich
  • 1,207
  • 10
  • 21
Andrew Lee
  • 10,127
  • 3
  • 46
  • 40
  • If they are ordered lexicographically, then wouldn't limit(...).on(...) return the first 50 items in the list? Also, what happens when there are less than 50 in the list? There would be no way to know since we would wait indefinitely in the on(...) call. I understand this doesn't apply to every case, but I'm really trying to grasp how things like pagination and ranges are going to work. – Kato Jul 13 '12 at 04:31
  • It will still return when it gets data, but it will simply have fewer than 50 records. We trigger value callbacks as soon as we hear a response from the server, whether or not there are N records available. – Andrew Lee Jul 23 '12 at 19:18
  • You can also use limit() in combination with startAt or endAt queries to do pagination, or to view the first 50 items, etc. – Andrew Lee Jul 23 '12 at 19:23