Yusuf-Uluc
Yusuf-Uluc

Reputation: 1065

FlutterFire update Array instead of replacing it

FireStore structure

so the menus field stores maps inside of an array/List. But when i want to add a map to menus it replaces all the existing ones with the new one, instead of adding a new one, here my code:

    Menu menuObj = Menu(
      name: menuName, categories: [
      Categories(
        name: categoryName,
      ),
    ]);

FirebaseFirestore.instance.doc('menus/${FirebaseAuth.instance.currentUser!.uid}')
        .set({
      'menus': [
        menuObj.toJson(),
      ]
    }, SetOptions(merge: true));

Upvotes: 0

Views: 846

Answers (1)

Yusuf-Uluc
Yusuf-Uluc

Reputation: 1065

I had to use this code instead:

    FirebaseFirestore.instance
        .doc('menus/${FirebaseAuth.instance.currentUser!.uid}')
        .set({
      'menus': FieldValue.arrayUnion([menuObj.toJson()])
    }, SetOptions(merge: true));

Important part is this: FieldValue.arrayUnion([menuObj.toJson()]).

Upvotes: 3

Related Questions