skip to Main Content

How can I append a new Map type in firestore?

void addUser() async {
    final us = _firestore.collection("users").doc(_search.text);
    us.update({
      "requests": (
        {_auth.currentUser?.email: rep}
      ),
    });
  }

Am using this method but the requests field in my firestore overwrites the previous one I want it to be appended. Any idea?

2

Answers


  1. The update() method will always overwrite your previous field with the new one, so achieving this with one operation using the update() is not possible, however, you can always get the current field from the document, then update its value, then save it again in the document like this:

    void addUser() async {
        final us = _firestore.collection("users").doc(_search.text);
        final currentDoc = await us.get(); // we get the document snapshot
        final docDataWhichWeWillChange = currentDoc.data() as Map<String, dynamic>; // we get the data of that document
    
        docDataWhichWeWillChange{"requests"]![_auth.currentUser?.email] = rep; // we append the new value with it's key 
        
        await us.update({
          "requests": docDataWhichWeWillChange["requests"],
        }); // then we update it again
      }
    

    But you should use this after being aware that this method will make two operations in your database, a get() and update().

    Login or Signup to reply.
  2. If you want to record multiple values, an array is an appropriate type. So, you could use the .arrayUnion method to record multiple entries.

    final washingtonRef = db.collection("cities").doc("DC");
    
    // Atomically add a new region to the "regions" array field.
    washingtonRef.update({
      "regions": FieldValue.arrayUnion(["greater_virginia"]),
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search