Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't add more than one document in the cloud firestore collection

I’m trying to save records in the cloud firestore using flutter. The thing is that it only adds one element and keeps updating its values whenever I add a new one through the app.

Here is my code:

Future addInterventionToDB(String userId, String etat, String op, String iv) {
    return FirebaseFirestore.instance
        .collection("interventions")
        .doc(userId)
        .set({
      'etat': etat,
      'operateur': op,
      'intervention': iv,
      'userId': user!.uid
    });
  }

and here is the function used in the UI part!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  String etatLabel = "";
  String operateur = "";
  String intervention = "";

  addIntervention(String etatt, String op, String iv) async {
    String currentUser = FirebaseAuth.instance.currentUser!.uid;
    if (currentUser != null) {
      DatabaseMethods().addInterventionToDB(currentUser, etatt, op, iv);
    }
  }

and here is the button where I did the call of the method:

onPressed: () async {
                    await addIntervention(etatLabel, operateur, intervention);                   
                  },

Noting that the values are extracted from chips (selected value of each chip).
I don’t know what’s wrong in here, tried updating the state of the variables each time a new selection takes place, but still having the same issue.

>Solution :

Since you passed the userId as the doc id, it keeps on overwriting it.

Replace

return FirebaseFirestore.instance
        .collection("interventions")
        .doc(userId)
        .set({
      'etat': etat,
      'operateur': op,
      'intervention': iv,
      'userId': user!.uid
    });

with

return FirebaseFirestore.instance
        .collection("interventions")
        .add({
      'etat': etat,
      'operateur': op,
      'intervention': iv,
      'userId': user!.uid
    });

But in this case, it adds random doc id. So you cannot fetch with userId. But you are already adding the userId as a field inside the document with this line 'userId': user!.uid. So you can fetch with that.

Hope it helps! Happy coding:)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading