Gajjar Tejas
Gajjar Tejas

Reputation: 188

Add child with automatically incremented custom ID - Firebase

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"
    });

Upvotes: 0

Views: 2859

Answers (2)

Sean Doherty
Sean Doherty

Reputation: 2378

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.

Upvotes: 0

alex kucksdorf
alex kucksdorf

Reputation: 2633

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.

Upvotes: 2

Related Questions