Home > Software engineering >  Adding map in Firestore?
Adding map in Firestore?

Time:01-02

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?

CodePudding user response:

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().

CodePudding user response:

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"]),
});
  • Related