0

I would like to add (or create if first) an array of map like this in my document:

videos
 - 0
  - url : myurl
 - 1
  - url : another one

by console I can do this, by I don't know how to do in code. This is my current set method:

await databaseReference.collection("${mycol}").doc("${mydoc}")
        .set({
          'url': url,
        });

and this adds a simple string to database. How Could I do this add an item in that structure I mentioned early?

Update

And what if I have this :

videos
 - 0
  - url : myurl
  - name : myname
 - 1
  - url : another one
  - name : myname

2 Answers 2

1

You can add array by:-

List<Map> videos=[
    {
      'url':'url',
      'name':'Harry',
    },
    {
      'url':'url',
      'name':'John',
    }
  ];
    await databaseReference.collection("${mycol}").doc("${mydoc}")
            .set({
              'url': FieldValue.arrayUnion([videos]),
            });

Now, if you have added 3 elements and in future wanna add 4th one then:-

List<Map> new=[
{
'url':'url for 4th video',
'name':'4th person name',
},
];
await databaseReference.collection("${mycol}").doc("${mydoc}")
                .update({
                  'url': FieldValue.arrayUnion([videos]),
                });

The purpose of FielValue.arrayUnion is that it automatically adds the new data to the firebase i.e. now you will have 4 elements in the array (3 previously added and 1 recently added).

Sign up to request clarification or add additional context in comments.

7 Comments

updated i hope it helps and if yes I request you to accept it as answer
But in this case I set there the content.. Can I 'merge' it? For example if there are 3 items, I want to add the fourth.. Did you understand me?
wait updating the answer.
Isn't automatic to check if there are elements (if yes update, if not set) ?
yes its automatic FieldValue.arrayUnion will append new element to list if not present then will create the array
|
1

You can do this in a similar way to what you are doing right there. For example:

await _firestore.collection(mycol).document(mydoc)
  .setData({
    'videos': arrayOfUrls,
    // OR
    'videos': mapOfUrls
  });

Firebase supports arrays and maps out of the box!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.