How to Create Auto Incremented Key in Firebase

Auto increment a value in firebase with javascript

Firebase has no auto-incrementing keys, since those don't work well in massively multi-user systems where clients can be offline for prolonged periods.

Instead, Firebase has its own type of auto-generated keys called push IDs. These push IDs have the same important properties of sequences in many relational databases: they are ordered and sequential. But in addition, they can be calculated client-side, even when the client is not connected to the Firebase servers.

See the Firebase documentation on saving data in lists, this legacy blog post on why arrays don't work well in Firebase and this post on how push ids work.

auto increment Id generator in firebase real-time database

So, firebase does provide a way to get the unique key when you push the changes, I am not sure if you have tried this:


postsRef.push({
author: "gracehop",
title: "Announcing COBOL, a New Programming Language"
});

// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();

// Get the unique key generated by push()
var postId = newPostRef.key;

You can check here for more details.

Or, if you want to create similar what Mongo does then you should create a custom one, create a similar key like Mongo does and keep it in the DB and on every new insert add that ID to the model. You can check here.

Firestore managing auto increment ID

Updated to use transaction and get the new number:

var docRef = firebase.firestore().collection('complaints').doc("autoincrement");

db.runTransaction(function(transaction) {
return transaction.get(docRef).then(function(incDoc) {

//if no value exist, assume it as 0 and increase to 1
var newIncId = (incDoc.data().number || 0) + 1;

transaction.update(docRef, { number: newIncId });
return newIncId;

});
}).then(function(newIncId) {
//`newIncId` This is your new number incremented

//use newIncId here
this.ticketnumber = newIncId;

console.log("New autoincremented number ", newIncId);
}).catch(function(err) {
// Catch block to get any error
console.error(err);
});

See doc https://firebase.google.com/docs/firestore/manage-data/transactions#passing_information_out_of_transactions


Why you're not using number: firebase.firestore.FieldValue.increment(1);?

This use transactions internally. But be aware that firestore document have the write limit of 1/sec. You can use RTDB if you expect to write more than once.

Auto-increment a value in Firebase

Here's an example method that increments a single counter. The key idea is that you are either creating the entry (setting it equal to 1) or mutating the existing entry. Using a transaction here ensures that if multiple clients attempt to increment the counter at the same time, all requests will eventually succeed. From the Firebase documentation (emphasis mine):

Use our transactions feature when working with complex data that could be corrupted by concurrent updates

public void incrementCounter() {
firebase.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(final MutableData currentData) {
if (currentData.getValue() == null) {
currentData.setValue(1);
} else {
currentData.setValue((Long) currentData.getValue() + 1);
}

return Transaction.success(currentData);
}

@Override
public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
if (firebaseError != null) {
Log.d("Firebase counter increment failed.");
} else {
Log.d("Firebase counter increment succeeded.");
}
}
});
}


Related Topics



Leave a reply



Submit