This is the data I have obtained from an excel sheet and I want to create firestore documents with the same id of kdocID variables and populate it's content from the remaining arrays:
List<String> kdocID = [
'5846',
'5846',
'5845',
'5844',
'5845',
];
List<String> kdate = [
'2.05.2023',
'2.05.2023',
'3.05.2023',
'2.05.2023',
'2.05.2023',
];
List<String> kuserID = [
'600PLN03',
'600PLN03',
'600PZR03',
'600PZR17',
'600PZR03',
];
List<String> kcompanyName = [
'Company 1',
'Company 1',
'Company 2',
'Company 3',
'Company 2',
];
List<dynamic> kcompanyID = [
1200204792,
1200204792,
1204000605,
1200200941,
1204000605,
];
List<dynamic> kentry = [
10,
20,
20,
10,
10,
];
List<dynamic> kentryProductID = [
20041976,
20041976,
30036627,
30053904,
30056608,
];
List<dynamic> kentryAmount = [
10,
1200,
3000,
150,
10000,
];
List<String> korderUnit = [
'KG',
'KG',
'M',
'M',
'M',
];
List<dynamic> kentryCost = [
30,
3600,
8190,
8650,
27800,
];
List<String> korderCurrency = [
'USD',
'USD',
'EUR',
'JPY',
'EUR',
];
The following structure is how I need to organize my database;
How can I achieve the previously shown structure with this obtained data? I have tried the following code but the problem with this code is that the arrays won't add duplicated values such as the case with the document 5846 where the field of entryProductID it's the same value twice.
for (var i = 0; i < kdocID.length; i++) {
db.collection('Orders').doc(kdocID[i]).set(
{
'date': Timestamp.fromDate(DateFormat('d.MM.yyyy').parse(kdate[i])),
'userID': kuserID[i],
'companyName': kcompanyName[i],
'companyID': kcompanyID[i],
'entry': FieldValue.arrayUnion([kentry[i]]),
'entryProductID': FieldValue.arrayUnion([kentryProductID[i]]),
'entryAmount': FieldValue.arrayUnion([kentryAmount[i]]),
'entryCost': FieldValue.arrayUnion([kentryCost[i]]),
'orderUnit': korderUnit[i],
'orderCurrency': korderCurrency[i],
},
SetOptions(merge: true),
);
}
If you want to allow duplicate data in an array field, you can't use the arrayUnion
operator to add it. By definition, that operator does not add duplicate.
There also is no arrayAdd
operator, so the only way to add duplicates is to:
If you expect that multiple clients may do this around the same time, be sure to use a transaction for the operation.