Reputation:
I want to have a document like below
But when i use the following code to add new document containing map it adds the data like the one shown in below picture
Firestore.instance.collection('users').document(some_docID).updateData({
'map1.key1': 'value1',
'map1.key2': 'value2'
});
Even if I use setData it still adds data as below, not as I wanted which is in the above picture.
Also one thing is that if the document is already present and it has at least one map field then if I use the above code it adds the data as map only. the problem is only when I want to create new document with map values. If anyone could suggest a solution would be great help.
Upvotes: 4
Views: 9457
Reputation: 483
There is are several differences between document.updateData
and document.setData
which need to be understood:
Firstly, you cannot create a document using updateData
. The document must be created before calling updateData
or the call will fail. This might have been the source of your problems.
You must use document.setData
. setData
requires that you specify your data in "nested" format, where fields are not "flattened" or "dot-delimited".
So for your example:
Firestore.instance.collection('users').document(some_docID).setData({
'map1': {
'key1': 'value1',
'key2': 'value2',
}});
If you want to guarantee that a document was previously created, then you should use document.updateData
(which as mentioned before, will fail if document
was not previously created).
updateData
requires that nested fields be specified in "dot-delimited" fashion.
So for your example:
updateData({
'map1.key1': 'value1',
'map1.key2': 'value2',
});
updateData
If you pass data in nested format to updateData
, it will assume that you wish to fully replace the value of a key with the subsequent data.
For example, if your document has data {'a': {'b': 2, 'c': 3}}
and you run updateData({'a': {'b': 4}})
the document will not just replace a.b
with 4
, but will also delete the c
field, since it was not included in the a
value passed to updataData
.
To only fields explicitly, use the dot-delimited format or setData(data, merge: true)
(see below).
setData
Note: You can also still use setData
to update data on a document. Still, the format required is "nested" and not dot-delimited.
If you wish to only update certain fields of document
explicitly, then pass merge: true
to setData
.
Upvotes: 14
Reputation: 80914
You have to add the data like this:
Firestore.instance.collection('users').document(some_docID).updateData({
"map1" : {
"key1" : "value1",
"key2" : "value2"
}
});
This will create a map in the database.
Upvotes: 2