Updating documents in Firestore is pretty easy.
One method is to use the update
function available in Firestore Library.
Update Method
Letβs look at an example by using the NoteModel class we created in Adding Data to Firestore article
final _db = FirebaseFirestore.instance;
NoteModel noteToUpdate = NoteModel(
title:"This is an Awesome Title",
content:"This is the Content of the Note",
);
await _db.collection("notes").doc("doc-id").update(noteToUpdate.toMap());
The above function will update the document with the document id we passed with the new data.
The One thing we should consider here is that, if there is no document existing with the document Id we provided, our Update will Fail.
This brings us to the second option.
Set Method
As I have pointed out in the article about adding data to Firestore, set function can be used to Add document with a custom Id to Firestore Collections.
It is also useful for updating a document. For that we have to pass merge:true
into setOptions
.
If we didnβt pass the merge:true
, the older document will be completely overwritten. But if we did this, the document will only update with new Data.
And this method will create a new document if no other document exists with the given document Id.
final _db = FirebaseFirestore.instance;
NoteModel noteToUpdate = NoteModel(
title:"This is an Awesome Title",
content:"This is the Content of the Note",
);
await _db.collection("notes").doc("doc-id").set(
noteToUpdate.toMap(),
SetOptions(
merge: true,
),
);
The above code will update a document if it exists and will create a new document if it exists.
Wrap
You can find more articles related to Firebase Here
Hope you found something useful here.
Iβm always open to suggestions!
Let me know your suggestions and opinions on Twitter DM or drop a mail a mukhtharcm@gmail.com.
If youβre feeling too generous, you can support me through Buy Me a Coffee.
Finally, if you found this helpful, please share this within your reach so that more people can benefit from this. And Follow me on Twitter for getting more posts like these π.
Top comments (0)