I want to add Map<> data to my firestore database with code :
Map<String, Object> prop = {
'read' : true,
'vote_left' : false,
'vote_right' : false,
};
Map<String, Object> attended_topic =
{
received_id:prop
};
FirebaseFirestore.instance.collection('userinfo').doc(user_now!.uid)
.update({"attended_topic": FieldValue.arrayUnion([attended_topic])});
What I expected is this.
attended_topic
topicId_0
read : true
vote_left : false
vote_right : false
But I got something unexpected.
attended_topic
0
topicId_0
read : true
vote_left : false
vote_right : false
I never expected that new category '0' appearing and donot know why. Since the atabase has other properties so I thought using update()
rather than set()
is adequate. Please somebody tell my why this happens.
CodePudding user response:
From the docs
FieldValue.arrayUnion
adds elements to an array but only elements not already present.
So {"a": FieldValue.arrayUnion([b])}
adds b
variable to the Array
a
.
To solve your problem, just remove FieldValue
as shown below.
FirebaseFirestore.instance
.collection('userinfo')
.doc(user_now!.uid)
.set({"attended_topic": attended_topic}, SetOptions(merge: true));
// use set method to add new data (not update)
// or
FirebaseFirestore.instance.collection('userinfo').doc(user_now!.uid).set(
{
'attended_topic': {
received_id: {
'read': true,
'vote_left': false,
'vote_right': false,
}
}
},
SetOptions(merge: true),
);
CodePudding user response:
I solved this problem referring Peter's solution and changing it slightly.
FirebaseFirestore.instance.collection('userinfo').doc(user_now!.uid)
.set({"attended_topic": attended_topic}, SetOptions(merge: true));