I want to update an array of IDs in a firestore document each time I add other documents to the collection.
And if the document does not exist yet (for the creation of the collection), create the document with the ID I want to add as the first value of that array.
So I want to try to update the document everytime and catch a possible error that would be "Some requested document was not found" and in that case create the document
as you can see here
void addDocument(Map<String, dynamic> docData, String docId) {
final db = FirebaseFirestore.instance;
db.collection(docId.trim().toLowerCase()).add(docData).then((value) {
try {
db.collection(docId).doc("doclist").update({
"list": FieldValue.arrayUnion([docData["id"]]),
});
} catch (_) {
Map<String, List<String>> listdata = {
"list": [docData["id"]],
};
db.collection(docId).doc("doclist").set(data);
}
});
}
So I wonder if it's a "clean" way of doing it, are try/catch are made to be used that way.
Or should I check if the doc exists with the doc.exists getter ? Since this fonction will be used quite often it would double the number of requests
CodePudding user response:
try catch
should be used for handling exceptions, which typically are not part of your normal flow control.
In this case for example, you can use set
with its merge option to create-or-update the document:
db.collection(docId).doc("doclist").set({
"list": FieldValue.arrayUnion([docData["id"]]),
}, SetOptions(merge: true));
This will create the document with a single item in the array if it didn't exist yet, or otherwise will add the item to the array of the pre-existing document. For more on this, see the second example in the documentation on setting a document.