0

This is an old question but no answers found. Old answers' source links are dead, old functions are deprecated.

I've look at these topics (1, 2) amongst others, and also current Firebase guide.

function writeUserData(name, win, loss) {
    firebase.database().ref('users/').push({
        name: name,
        wins: win,
        losses: loss
    });
}

I need to pull or somehow convert the unique ID from each push to numeric ID: 1, 2

UPDATE:

Here's what I'm trying to do:

  • 2 users can login at the same time from 2 different browsers.
  • 1st user hits button 'log-in' or 'start' will be written as users/1/{user's attributes} on firebase.
  • if there's an existing user (somehow I need to check that on the user-end), the next user hits 'start' will be written as users/2/{user's attributes} on firebase. Else (no existing user), the user will be written as user1. This is where I think I need push instead of set. I can use set to add more users from 1 browser, but if i open the app from another browser/chrome incognito, the app will just reset the existing users.
  • if a user refreshes or closes the browser, that user will be removed from firebase so another user can log-in.

I've tried different methods (loop, creating new var...) to achieve this.

halfer
  • 19,824
  • 17
  • 99
  • 186
Viet
  • 6,513
  • 12
  • 42
  • 74
  • Why? What is it you are trying to achieve? – cartant Sep 15 '17 at 01:58
  • I need numeric ID because I need to update wins and losses after each round. With the generated IDs, I cannot access the data. – Viet Sep 15 '17 at 02:05
  • Why can you not access the data? – cartant Sep 15 '17 at 02:42
  • 1
    This appears to be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – cartant Sep 15 '17 at 02:43
  • Using numeric sequential IDs in Firebase Database is most often an anti-pattern. See [this post](https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html) for more. Cartant is right: tell us what you're trying to accomplish, instead of how you're trying to solve it. – Frank van Puffelen Sep 15 '17 at 03:14

1 Answers1

0

Rather than .push, try to use .set or .update. In that way you can set your own generated key. But as already suggested, this may not be the best approach.

raju
  • 6,448
  • 24
  • 80
  • 163