skip to Main Content

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


  1. 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 the Videos field if it doesn’t exist, and it will add the 2022-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:

    1. Read to read the document.
    2. Get the Videos map in memory.
    3. Check if a video already exists.
    4. Add the new map inside the Videos.
    5. Write the document back to Firestore.

    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.

    Login or Signup to reply.
  2. 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:

    db.collection('Collection').doc('Document').update({
        'Videos.2022-Oct-03-14:55.Title': 'Ok'
    });
    

    Also see the Firebase documentation on updating a field in a nested object.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search