How to use startAt() in Firebase query?
Solution 1
The case with your query is that it's expecting that the message
node should have a number value to start with, in that case you want a child node with the name createdAt
. So in that case you must specify that you want to order by createdAt
, thus you need to do this
firebase.database().ref(`/rooms/$roomKey/messages`).orderByChild('createdAt').startAt('15039996197').on(//code);
This way it'll return all nodes inside message
that has a child named createdAt
an it starts at 15039996197
. Ordering your query may be a little bad for performance, for that i sugest taking a look at .indexOn rule.
For more information take a look here.
Hope this helps.
Solution 2
Firebase Data Retrieval works node by node. So whatever data you want to get, the entire node is traversed. So in your case to get any message your complexity would be O(number of messages).
You would want to restructure the way you are storing the data and put createdAt in Node instead of Child.
Comments
-
ton1 about 2 years
Let's suppose above firebase database schema.
What I want to is retrieve messages which after "15039996197" timestamp. Each of message object has a
createdAt
property.How can I get messages only after specific timestamp? In this case, last two messages are what I want to retrieve.
I tried
firebaseb.database().ref(`/rooms/$roomKey/messages`).startAt('15039996197')
but failed. It return 0. How can I do this? -
ton1 almost 7 yearsAs your recommend, I use timestamp as a key. but
fb.database().ref(
/rooms/$roomKey/messages).startAt(timestamp)
won't work. any Idea ?? -
Frank van Puffelen almost 7 yearsThe JSON shows that the timestamp is stored as a number, so
.startAt(15039996197)
. -
ton1 almost 7 years@FrankvanPuffelen Hi. Can I ask you something? Do you know which is proper data schema?
1. Use timestamp as a key like Rishabh's answer
vs2. Use my previous data schema and query with .orderByChild and .startAt
-
ton1 almost 7 yearsI am trying to use timestamp as a key, but the query failed.
fb.database().ref(/rooms/$roomKey/messages).startAt(timestamp)
-
Frank van Puffelen almost 7 yearsThere is no singular proper schema, it always depends on the use-cases of your app. But the fact that you don't get results with your current query is due to two problems in the code: 1) you need to call
orderBy("createdAt")
(as Gabriel shows in is answer) 2) you need to pass a number tostartAt()
since you store the timestamps (correctly) as numbers. -
André Kool almost 6 yearsThis would only get messages with that specific timestamp, not all the messages after that timestamp.