0

I want to add a new user to firebase database with auto increment id as shown below screenshots:

enter image description here

I have tried:

    var rootRef = firebase.database().ref();
    var storesRef = rootRef.child("/users");
    storesRef.set({
      "name": "user1",
      "pageId": "user1"
    });
alex kucksdorf
  • 2,573
  • 1
  • 15
  • 26
Gajjar Tejas
  • 188
  • 5
  • 20
  • Do you need the user ids to be `0,1,2,...`? Otherwise, you could use Firebases built-in ID generation, which also preserves the order of creation, because it takes the time of creation into account. – alex kucksdorf Dec 05 '17 at 11:48
  • @alexkucksdorf yes, user id needed. Because I have imported from quickblox – Gajjar Tejas Dec 05 '17 at 11:50
  • 1
    As Alex said: using sequentially, monotonously incrementing IDs like that is going to be a serious hinder to both the scalability and the offline behavior of your app. I recommend you read the Firebase blog post on this: https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html – Frank van Puffelen Dec 05 '17 at 15:31

2 Answers2

2

I do not recommend this, but you can try the following:

storesRef.limitToLast(1).once('value', (snapshot) => {
    const nextID = parseInt(snapshot.key) + 1;
    let updates = {};
    updates['/users/' + nextID] = // your user;
    rootRef.update(updates);
});

However, I would strongly suggest you use Firebases automatically generated IDs instead, since this approach is very error prone.

You should also have a look at this answer.

alex kucksdorf
  • 2,573
  • 1
  • 15
  • 26
0

I spent a long-ish time trying to solve this problem for my own project and as usual it turned out to be deceptively easy:

var newUserIndex;

storesRef.on('value', snap =>{
  newUserIndex = snap.val().length;    
});

database.ref('users/' + newUserIndex).set({name:'user1', pageId:'user1'});

Because the database is zero-based, snap.val().length always gives the next index needed. I thought using snap may be overkill for this and a waste of resources (I've only just started using Firebase so still getting to grips with it) - but checking the usage stats in console, apparently not.

Not everyone is building an app that has multiple users and needs scalability. I understand the benefit of using auto generated keys using push() but it's not always the right solution for smaller projects and single user projects.

Sean Doherty
  • 2,273
  • 1
  • 13
  • 20