In my code I want to increment the usage by the value 1. I have the usage in firebase and I use it in a chart. I use this function to increment by the value 1:
addActivity(
int day,
) async {
final documentSnapshot = await FirebaseFirestore.instance
.collection('users')
.doc(FirebaseAuth.instance.currentUser!.uid.toString())
.collection('activity')
.doc('${globals.year}')
.collection('week${globals.week}')
.doc(day.toString())
.set({'usage': FieldValue.increment(1)});
}
The problem is that whatever I do the usage value is always set to the value that is in the braces (now 1). I tested this with multiple values and it doesnt seem to work. When I change the initial value to 2 the value after tapping the button isnt 3 but 1...
I'm open and thankful to/for all suggestions :)
CodePudding user response:
That way it's written now using set()
, your code always going to overwrite the contents of the document. If you want to update a document, you should use update()
instead to update an existing document, or set()
with the merge option (SetOptions(merge: true)
).
.set({'usage': FieldValue.increment(1)}, SetOptions(merge: true));
CodePudding user response:
To achieve the desired effect you should use update
method. set
overrides data so it actually sets 1 each time for you. So, just refactor to this
.update({'usage': FieldValue.increment(1)});