Mohammed
Mohammed

Reputation: 15

how to write nested array in Firestore using flutter

Building a shopping app I added a cart item in my 'users' collection.

cart stored in

and after the user purchase those item I wanted to store those cart items in other collection 'orders'. but when I tried to store those cart items in my order collection firebase throws Invalid data. Nested arrays are not supported.

what is my mistake here?

Here is my Code

onPressed: (){
                //orderItem(cartItem);
                getData() async {
                  return await FirebaseFirestore.instance.collection('users').where('id', isEqualTo: FirebaseAuth.instance.currentUser.uid).get();
                }
                getData().then((val){
                  if(val.docs.length>0){
                    //print(val.docs[0].data()['cart']);

                   // Map map = val.docs[0].data()['cart'];
                    var list = [val.docs[0].data()['cart']];
                    // map.entries.forEach((e) {
                    //   list.add();
                    // });
                   // List items = [val.docs[0].data()['cart'].toList()];
                    FirebaseFirestore.instance.collection('orders').doc().set({
                      "userId": FirebaseAuth.instance.currentUser.uid,
                      "userName": FirebaseAuth.instance.currentUser.displayName,
                      "orders": FieldValue.arrayUnion([[val.docs[0].data()['cart']]]),
                      "price": cartController.totalCartPrice.value
                    });
                  }
                  else{
                    print("Not Found");
                  }
                });
                

              },

Upvotes: 1

Views: 566

Answers (2)

Dharmaraj
Dharmaraj

Reputation: 50830

Arrays in a Firestore documents cannot contain arrays so you cannot have have something like:

[
  [orderId: 1, orders: [...orders]],
  [orderId: 2, orders: [...orders]],
  
  //This is possible
  {orderId: 3, orders: [...orders]}
]

enter image description here

If you try adding a document from the console itself, you'll notice the same.

The best you can do is store the orders as a string, [JSON.stringify(ordersObject)]. Then when you fetch the data back you can parse it into as JSON again..

Second option is restructuring your data, it would have ideal to have a separate collection for orders. Then you can use .where() queries to fetch orders of a specific user. However this'll be more expensive (but ideal) because you will be fetching 12 documents (12 reads) if user has 12 orders.

Upvotes: 1

pr0gramista
pr0gramista

Reputation: 9008

I think the problem is trivial. You accidentally put list inside list.

"orders": FieldValue.arrayUnion([[val.docs[0].data()['cart']]]),

I think you can skip one pair of [ so you have this:

"orders": FieldValue.arrayUnion([val.docs[0].data()['cart']]),

Also... if val.docs[0].data()['cart'] is a list you'll probably need to skip another pair to this:

"orders": FieldValue.arrayUnion(val.docs[0].data()['cart']),

Upvotes: 1

Related Questions