Auto-increment A Value In Firebase
Answer :
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."); } } }); }
A new feature is added to firestore to autoincrement values. As simple as
document("fitness_teams/Team_1"). updateData(["step_counter" : FieldValue.increment(500)])
refer link: https://firebase.googleblog.com/2019/03/increment-server-side-cloud-firestore.html
Used below code in my project.
var firestore = Firestore.instance; firestore.collection('student').document('attendance').updateData({'total_attendace': FieldValue.increment(1)});
Comments
Post a Comment