0

I have one collection called Audiolibros (audiobooks) in Cloud Firestore. Each document of this collection has one field called idAutor (idAuthor) that it's a Reference field from a collection called Autores (authors).

Reference field in Audiolibros collection

I want to get the information inside the Autores's document by the author's id saved in an Audiolibro's document. I don't mind if I have to get the author id from Audiolibros and then use it in other method to get the author information getting the document by that id, or if I can get all the content of that author in the same method, but the fact is that it's been impossible for me to get that information.

Author's document content

I've tried many things, but the problem is that, when I get the idAutor field, I don't get it as a DocumentReference, as I've seen in other responses, I get it as a _JsonDocumentReference. And no matter what I do, I don't know how to extract the author id from a _jsonDocumentReference. Probably it's easier than I think, but I don't know how to do it. Anyone knows how to get the author's information from a reference field of its id?

_JsonDocumentReference

In the method I have, I want to get the author information for every audiobook in the list of audiobooks. This is one of the multiple options I've tried:

    Future<List<Audiolibro>> getAudiolibros() async{
    List<Audiolibro> listaAudiolibros = [];

    CollectionReference audiolibros = bbdd.collection("audiolibros");
    QuerySnapshot<Object?> response = await audiolibros.get();

    response.docs.forEach((element) {
      final data = element.data();
      final datos = data as Map<String, dynamic>;
      var rutaAutorAudiolibro = datos['idAutor'] as DocumentReference<Map<String, dynamic>>;

      //I don't know how to continue from this point to get the author information

    });

    return listaAudiolibros;
    }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0
  • _JsonDocumentReference is just the class that implements DocumentReference in FlutterFire, so a _JsonDocumentReference is also a valid DocumentReference.
  • Since rutaAutorAudiolibro is a DocumentReference, you can call get() on it to get the corresponding DocumentSnapshot.
  • If you want to await the loading of the author, you'll need to use for...in or Future.await() rater than forEach. See How to Async/await in List.forEach() in Dart
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    Yess! It was exactly that! Thank you for you answer, I'm new to Flutter and Cloud Firestore and No SQL DB and I'm a bit lost hahaha. Finally, I put the code like this: ` await Future.forEach(response.docs, (element) async { final data = element.data(); final datos = data as Map; var rutaAutorAudiolibro = datos['idAutor'] as DocumentReference>; var rutaAutorSnapshot = await rutaAutorAudiolibro.get(); final datosAutorSnapshot = rutaAutorSnapshot.data() as Map; ` – nurilu jaja Mar 11 '23 at 20:01