0

I am trying to use keys to sort my data from latest to oldest. My first option is to use unique keys in reverse order(latest will be on top), so first I used negative timeStamp as keys. But keys in firebase are string so it won't work. That's why I decided to use [9999999999999 - date.now()] as key in firebase and it works(rendered reversely). Is it safe to use this method? Why using child is the best way to sort data? Why not keys?

firebase.database().ref('saved_phrases')
    .child(firebase.auth().currentUser.uid)
    .child([9999999999999-Date.now()]).set(
      "phrase"
    )
1
  • 1
    This is pretty vague; what does push keys in reverse order mean exactly and more importantly why would you want to do that? Also, using keys for ordering may not be the best idea - you may be better off storing a timestamp as a child node and ordering by that. If you store a + child node and then a - child node you can read them ascending or descending at any time. Commented Jul 4, 2018 at 12:47

1 Answer 1

3

It is totally valid to create your own keys, as long as your app guarantees that these keys are unique. So if a user in your app can only ever create a single saved phrase per millisecond (the granularity of Date.now()), you should have no chance of getting the same key multiple times. But you should only use these keys if you can guarantee these keys will be unique - not just now but also for the future of your app.

If you're not completely certain of this, consider storing the timestamp as a property, the inverse timestamp as another property, and then use orderByChild() to get the behavior you need.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.