Im writing an app in flutter, and im trying to make a messages document that stores a list of messages using the following:
Future<void> updateStingrayMessageForLike(
String chatId, String? stingrayid) async {
return FirebaseFirestore.instance
.collection('stingrays')
.doc(stingrayid)
.collection('messages')
.doc(chatId)
.set({'messages': []}, SetOptions(merge: true))
.then((value) => print("User Updated"))
.catchError((error) => print("Failed to update user: $error"));
}
The problem is, this method is called in a case where a user enters a message screen, but a message document has not been created yet. So if the user adds messages, leaves the screen, then comes back, the document will reset its messages to an empty array object. Is there a way to only create/update a document if does not exist?
2
Answers
There is no built-in method for this. You will have to first read the document, check to see if it exists, then create the document if it does not already. The safest way to do this is in a transaction that performs the read and write atomically so that two apps will not clobber each others’ data.
In addition to the transaction approach that Doug describes, you can (and probably should) also use security rules to reject the write operation if the document already exists. For example you can validate the data being written to ensure it meets your requirements.