Firestore — запрос, где ключ карты

#flutter #dart

#flutter #dart

Вопрос:

Я создаю приложение для сканирования штрих-кодов, в котором оно обновляет статус товара в заказе, если он сканируется. У меня уже 3 глубоких запроса, и я знаю, что это начинает ошибаться.

Моя конечная цель должна быть такой:

Barcode scan -> query current order number -> query item number (if included in the order) -> update

Содержимое Firestore:

Содержимое Firestore

         var result = await BarcodeScanner.scan();
        var find = result.rawContent;

        Firestore.instance
            .collection('srs-items')
            .document(docId)
            .get()
            .then((DocumentSnapshot documentSnapshot) {
            
                print("Val: "   documentSnapshot.reference.path);
                    message = "Item scanned";

                    // I got lost here

                   // This query should be where('9781452103068', isEqualTo: find)
                   // or whatever the dynamic way to call the key of the map


                    Firestore.instance
                        .collection('srs-items')
                        .where(documentSnapshot.reference.path   "/$find", isEqualTo: find)
                        .limit(1)
                        .getDocuments()
                        .then((QuerySnapshot querySnapshot) {
                            print(querySnapshot.documents.length.toString());
                            if(querySnapshot.documents.length == 0)
                                message = "Item not in SRS listings";
                            else {
                                message = "Item scanned";

                                // not sure if there's a need for 3rd query for updating 9781452103068's status

                                /*Firestore.instance
                                    .collection('srs-items')
                                    .document(docId)
                                    .updateData({
                                    "$find.status": "2"
                                });*/
                            }
                            print(message);
                            _showToast(context, message);
                        });
               
                
            })
            .catchError((onError) {
                print(onError.toString());
            });
  

Комментарии:

1. На мой взгляд, вам следует раскомментировать часть обновления, и она должна работать. В чем ошибка? Я не знал результата, но когда я прочитал, это имеет смысл.

2. у @JasonSimard возникла эта ошибка во время 2-го java.lang.IllegalArgumentException: Use FieldPath.of() for field names containing '~*/[]'.

Ответ №1:

Проблема решена. Я добавил if(key == find) {} , прежде чем перейти ко 2-му запросу. Итак, окончательный код выглядит следующим образом:

  var result = await BarcodeScanner.scan();
        var find = result.rawContent;
        String message = "";
         Firestore.instance
            .collection('srs-items')
            .document(docId)
            .get()
            .then((DocumentSnapshot documentSnapshot) {
                documentSnapshot.data.forEach((key, value) {

                    if(key == find) { // <--- added this

                        message = "Item scanned";
                         Firestore.instance
                            .collection('srs-items')
                            .where( FieldPath.documentId , isEqualTo: find)
                            .limit(1)
                            .getDocuments()
                            .then((QuerySnapshot querySnapshot) {
                            Firestore.instance
                                .collection('srs-items')
                                .document(docId)
                                .updateData({
                                "$key.status": "2"
                            });
                        })
                        .catchError((onError) {
                            print("Err: "   onError.toString());
                        });
                    }
                    else {
                        message = "Item not in SRS listings";
                    }
                });
            })
            .catchError((onError) {
                print("Err: "   onError.toString());
            });