Home > database >  How do I add a new Map entry to a Map without overwriting the entire Map?
How do I add a new Map entry to a Map without overwriting the entire Map?

Time:10-03

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?

CodePudding user response:

There is no way you can add a new object to the Videos map without reading the document 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. Add the new map inside the Videos.
  4. Write the document back to Firestore.

But note, if you'll have a map with the exact same as a previous key, then the data will be overwritten.

  • Related