Reputation: 188
I want to add a new user to firebase database with auto increment id as shown below screenshots:
I have tried:
var rootRef = firebase.database().ref();
var storesRef = rootRef.child("/users");
storesRef.set({
"name": "user1",
"pageId": "user1"
});
Upvotes: 0
Views: 2859
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
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