Reputation: 143
As per the question I'd like to add a new array every time I call my addPredection function for example I'd like it to look like this.
Currently its just updating the current value everytime
My code is as follows:
///add prediction function
Future<String?> addPrediction() async {
var currentUser = FirebaseAuth.instance.currentUser;
var todaysDate = DateTime.now().toString();
var doesExist = await FirebaseFirestore.instance
.collection('collection')
.doc(currentUser!.uid)
.get();
if (doesExist.exists == true) {
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.uid)
.update({
'Predictions':
FieldValue.arrayUnion([todaysDate,'angry', 'Happy'])
});
}
if (doesExist.exists == false) {
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.uid)
.set({
todaysDate: FieldValue.arrayUnion(['angry', 'Happy'])
}, SetOptions(merge: false));
}
Upvotes: 1
Views: 81
Reputation: 2779
For adding items you also have to apply the SetOptions but with the merge set to true, like this:
var todaysDate = DateTime.now().toString();
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.UID).set({
todaysDate : ['angry', 'happy']
}, SetOptions(merge: true));
I did it on my end and I believe they come out the way you want:
The merge: true on the SetOptions what it does is that it appends to the existing document. The set method by default overrides the existing fields unless the merge: true option is there.
Upvotes: 1