jremi
jremi

Reputation: 2969

orderByChild and startAt firebase realtime using Date timestamp not returning data

- foo
|--- -LK7rNAPKZP7drHK1eb_
      |- timeStamp: 1534966072658
|--- -LKAPfu2lLl2B5zInIhX
      |- timeStamp: 1534965117552
|--- -LKJN97VxOhnE8XoNSQN
      |- timeStamp: 1534946072623

db.ref('foo').orderByChild('timeStamp').startAt(Date.now().toString()).limitToLast(7).once('value', data => {
    console.log(data.val());
}

The result is null. When I don't put the .startAt I am able to get data and it actually is sorted by timestamp... However, I need to be able to set the startAt since I am doing an infinite scrolling and I need to be able to specify the last timeStamp record. What am I doing wrong? I want to pull the first 7 records

Using firebase realtime db

Upvotes: 0

Views: 1087

Answers (1)

CRice
CRice

Reputation: 32146

In short, don't call toString() on Date.now(), just leave it as a number.


From firebase docs:

4: Children with a numeric value come next, sorted in ascending order. If multiple children have the same numerical value for the specified child node, they are sorted by key.

5: Strings come after numbers and are sorted lexicographically in ascending order. If multiple children have the same value for the specified child node, they are ordered lexicographically by key.

As you can see, string values are always sorted after numbers, so by specifying a string on your startAt, you have guaranteed that no entry with a numeric value for that field will be in the result. Since all your entries are numeric, that means your result is null.

Upvotes: 1

Related Questions