Sana'a Al-ahdal
Sana'a Al-ahdal

Reputation: 1780

how to search for a document in firestore by its reference

I have two collection, one is normal collection , and the other one is holding the documentReference for the first one , what I want is to do is giving me the specific document by its reference , I find the specific document by searching in for loop, but is there any better way to do that , without geting all the document from the first collection , just get the only one that i need .

static Future<List<author_model>> getTHEauthor(DocumentReference documentReference) async{
    String ref = documentReference.documentID;
    DocumentReference dReference = articleCollection.document(documentReference.documentID);
    List<author_model> author=[];
    author_model model ;
    final QuerySnapshot querySnapshot = await authors.getDocuments();
    List<DocumentSnapshot> result = querySnapshot.documents;

    for(int i=0 ; i<result.length ; i++) {
      if (result[i].documentID == ref) {
          model = new author_model(
           result[i]['author_name'], result[i]['author_image'],
           result[i]['author_work_exeperience']
           , result[i]['autor_education']);
           author.add(model);
         break;
      }
    }
    // print(author.length);
    return author;
  }

also I tried this one , but give me nothing

var snap = documentReference.get();
author_model m = author_model.map(snap);
print(m.author_name + ": " + m.author_education)

Also tried this query

 final QuerySnapshot querySnapshot = await authors.where('documentID', isEqualTo: 
  ref).getDocuments();

but no result, I don't know how to get only the document with the specific reference. I don't want to get all the document in the authors collection ,

Can anyone help me to how to query and get only for the specific document , please ?

Upvotes: 0

Views: 197

Answers (2)

Sana&#39;a Al-ahdal
Sana&#39;a Al-ahdal

Reputation: 1780

I used this code , i used stream builder @gso_gabriel

Stream authorStream ;



@override
void initState() {
authorStream=Firestore.instance.collection('doctors_authors').document(_article.author_reference.documentID).snapshots();
super.initState(); }



  child: StreamBuilder(
       stream: authorStream,
      builder: (context, snapshot) {
       if (snapshot.hasData) {
        return Column(
          children: <Widget>[
            SizedBox(height: 30,),
            GestureDetector(
              child: CircleAvatar(
                radius: 50,
                backgroundImage: NetworkImage(snapshot.data['author_image'].toString()),),

Upvotes: 1

gso_gabriel
gso_gabriel

Reputation: 4660

I would recommend you to take a look at the question already answered here: Finding all docs with specific reference in Cloud Firestore

It seems that this very related to your case and the solution should definitely help you. :)

Let me know if the link helped you!

Upvotes: 1

Related Questions