Joshua Foxworth
Joshua Foxworth

Reputation: 1397

Angular Firestore query with where returns all docs in collection

I have an angular app that is using Firestore. Whenever I query for docs in collection that meet a specific condition, the array that is returned contains every document in the collection. I do not understand why this is happening as I am following the documentation.

On call to the collection in the component

this.FirebaseService.getDocsByParam( 'versions', 'projectId', this.projectData.uid )
    .then((snapshot) => {
        var tempArray = [];
        var docData;
        snapshot.forEach((doc) => {
            docData=doc.data();
            docData.uid=doc.id;
            tempArray.push(docData);
        });
        this.versionList = tempArray;
        this.versionData = this.versionList[this.versionList.length-1];
        this.initializeAll();
    })
    .catch((err) => {
      console.log('Error getting documents', err);
});

Firebase service making the call

getDocsByParam( collection, getParam:string, paramValue:string ) {
    var docRef = this.afs.collection(collection, ref => ref.where(getParam, '==', paramValue));
    return docRef.ref.get();
}

Below is a screen shot of the versions collection. It shows one of the returned docs, which does not even have the required field.

enter image description here

Upvotes: 1

Views: 3242

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600006

When you call docRef.ref on a AngularFirestoreCollection it returns the underlying collection, not the query. So your return docRef.ref.get() is indeed getting the entire collection.

I think you can use docRef.query to get the query, but I don't even thing there's any reason to use an AngularFire call at all here. Since your code is already using the plain JavaScript API to process the documents, you might as well stick to that SDK in your getDocsByParam too:

getDocsByParam( collection, getParam:string, paramValue:string ) {
    var docRef = this.afs.collection(collection).ref;
    return docRef.where(getParam, '==', paramValue).get();
}

Upvotes: 2

Related Questions