Please help solve this issue. I have a list of records that I want to upload as an array to Cloud Firestore document. On the press of the button the list is getting added as individual documents as an array though. What I want is to be added in a single document as array, everytime I click on add button.
Please see the image below how I am trying to upload data:
Instead of the above this is how the individual records are getting added:
This is my toJson map inside my model class:
Map<String, dynamic> toJson(RecordModel records) {
return {
'murajaatRecords': FieldValue.arrayUnion([
{
'juz': records.juz,
'surah': records.surah,
'page': records.page,
'grade': records.grade,
}
])
};
}
This is my Firebase Cloud Firestore function to upload data:
Future<void> markMurajaat({required RecordModel recordModel}) async {
final docRef = _firebaseFirestore
.collection(FirestoreConstants.pathUserCollection)
.doc(_firebaseAuth.currentUser!.uid)
.collection(FirestoreConstants.pathMurajaatRDCollection)
.doc();
FirebaseFirestore.instance.runTransaction((transaction) async {
final snapshot = await transaction.get(docRef);
if (!snapshot.exists) {
//final updateRecord = snapshot.get(docRef);
transaction.set(docRef, recordModel.toJson(recordModel));
} else {
var docId = docRef.id;
final newDoc = _firebaseFirestore
.collection(FirestoreConstants.pathUserCollection)
.doc(_firebaseAuth.currentUser!.uid)
.collection(FirestoreConstants.pathMurajaatRDCollection)
.doc(docId);
transaction.update(newDoc, recordModel.toJson(recordModel));
}
}).then((value) => print('Record updated'),
onError: (e) => print('Error updating record $e'));
}
Inside my controller class I have this method, when user clicks on the button records gets added and then uploads to Cloud Firestore.
void markRecord(RecordModel records) async {
recordModel.add(records);
final avgValue =
recordModel.map((element) => element.grade as double).toList();
averageGrade.value = avgValue.average;
try {
await _firestoreFunctions.markMurajaat(recordModel: records);
} on FirebaseException catch (e) {
if (kDebugMode) {
print(e);
}
}
}
My button where from where records are being added:
GFButton(
color: AppColors.spaceCadet,
elevation: Sizes.dimen_6,
size: GFSize.MEDIUM,
text: 'MARK',
fullWidthButton: true,
onPressed: () {
var muraRecord = RecordModel(
juz: controller.juzString.value,
surah: controller.surahString.value,
page: controller.pageString.value,
grade: controller.grade.value,
);
controller.markRecord(muraRecord);
controller.grade.value = 10.0;
},
),
These are the list of records that I am trying to upload:
I am not sure what my mistake is here. Why each record is being added as individual document and under a single document. Please help me figure this out. Appreciate if someone can advise. Thank you in advance!


