In my Firestore database, I have a document with a Map called ‘Videos’.
In it, I add another Map into it that includes my video data.
So it looks like this:
Videos (Map) :
2022-Oct-03-14:24 (Map):
Title: Hi
Now what I want to do is, add another Map to the Videos
with a different date.
How do I do this in Flutter?
Currently, I am doing:
db.collection('Collection').doc('Document').update({
'Videos': {
'2022-Oct-03-14:55': {
'Title': 'Ok'
}
}
});
But what this does is, it overrides the entire Videos
map and assigns this new map I give, so the old Map with the Title Hi
gets deleted. How do I insert new maps?
2
Answers
For adding a new object inside the
Videos
map, you have two options available. The first one would be to use the.
(dot) notation, as @FrankvanPuffelen mentioned in his answer, which will work perfectly fine. This means that it will indeed create theVideos
field if it doesn’t exist, and it will add the2022-Oct-03-14:55
subfield inside it if that doesn’t exist, and then the Title you put in there. However, since it’s an update operation, this solution will work only if the document already exists, otherwise, it will fail.If you need to create the
Videos
field inside a document that doesn’t already exist, then you should consider using the set() function with merge true. However, this solution doesn’t work using the.
notation. So for that, I recommend you check my answer in the following post:The second solution would be to read the document/map first. It’s not mandatory but it will help you check the existence of an existing object. Why, because those objects are maps, and when it comes to maps, if you add a record that has the same key, then it replaces the old value with the new one. So I recommend you have to check that first.
So in order to perform the addition operation, you have to:
Videos
map in memory.Videos
.If you’ll have a map with the exact same key as a previous key, then the data will be overwritten, meaning that you’ll don’t see any change in the key, but only in the value if it’s different.
While Alex’s answer is correct if you had an array field, you only have map fields. In that case, you can use
.
notation to updates/write only the nested field:Also see the Firebase documentation on updating a field in a nested object.