0

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.

2 Answers 2

2

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),
);
Sign up to request clarification or add additional context in comments.

2 Comments

It seems that set() removes all other data in the target doc. Can you please suggest me some supplementary ?
Simply use SetOptions(merge: true). I will update my answer to show this.
1

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));

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.