Constantin Chirila
Constantin Chirila

Reputation: 2119

Firebase Firestore Increment FieldValue does not increment

so i've read all the documentation everything about increment a counter in a Firestore database. I have this code

const admin = require("firebase-admin");
const db = admin.firestore();
...
db
.collection("settings")
.doc("totalUsers")
.set({
count: firebase.firestore.FieldValue.increment(1),
});

And i just doesn't increment the counter at all. No errors no logs no nothing. In my Firestore i have a collection of settings and a document totalUsers with a property count that is a number type and it equals to 1.

Am I doing something wrong? Am I missing anything? Any help appreciated!

Upvotes: 13

Views: 5768

Answers (4)

Mauricio Durcak
Mauricio Durcak

Reputation: 1

Try with this: (this is my code and works for me)

var firebaseUser = await FirebaseAuth
                        .instance
                        .currentUser();
DocumentReference query = Firestore.instance
                              .collection("users")
                              .document(firebaseUser.uid);
                                                    Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => LoginView()));
 var loginSuccess = wait model.getdata(_inputCuit.text);

 if (loginSuccess) {
     query.updateData({ "queries": FieldValue.increment(1)});
 }

The key area is the .increment() method

Upvotes: 0

Louis Coulet
Louis Coulet

Reputation: 4631

increment works with both update and set.
For it to actually increment the field you can:

  • use update, but the documents must exist already
  • use set with option merge: true or mergeFields: "something", with something the name of the field being incremented

Upvotes: 12

Constantin Chirila
Constantin Chirila

Reputation: 2119

For anyone having issues with this, be careful to use the .update() method instead .set(). Also you need to have a value existing in the firestore that so it has something to increment.

Upvotes: 5

Renaud Tarnec
Renaud Tarnec

Reputation: 83068

Since you are using the Admin SDK, you should do as follows:

count: admin.firestore.FieldValue.increment(1)

Upvotes: 3

Related Questions