angular / angularfire

Angular + Firebase = ❤️
https://firebaseopensource.com/projects/angular/angularfire2
MIT License
7.66k stars 2.19k forks source link

Ability to add additional queries after a Firestore collection reference is created? #2500

Closed EdricChan03 closed 3 years ago

EdricChan03 commented 4 years ago

Version info

Angular: 9.0.2

Firebase: 7.13.1

AngularFire: 6.0.0

Other (e.g. Ionic/Cordova, Node, browser, operating system): NodeJS 13, Chrome 83.0.4103.61, macOS 10.14.6

How to reproduce these conditions

Failing test unit, Stackblitz demonstrating the problem

Steps to set up and reproduce

It's currently not possible to add additional queries after a Firestore collection reference is created.

(For context, I'm creating the ability to view recently added chat groups in the past month which are public.)

lastMonthDate = new Date();
publicChats$: Observable<Chat[]>;
recentChats$: Observable<Chat[]>;
publicChatCollection: AngularFirestoreCollection<Chat>;
constructor(
  private afFs: AngularFirestore,
  /* ... */
) {
  this.publicChatCollection = afFs.collection<Chat>('chats', query => query.where('visibility', '==', 'public'));
  this.recentChats$ = afFs.collection<Chat>('chats',
    query => query.where('visibility', '==', 'public')
                  .where('createdAt', '>=', this.lastMonthDate)
    ).valueChanges({ idField: 'id' });
  this.publicChats$ = this.publicChatCollection.valueChanges({ idField: 'id' });
}

Sample data and security rules

{
  "chats": {
    "<uniqueId>": {
      "visibility": "public",
      "createdAt": "<Timestamp object>",
      "owner": "<DocumentReference object>",
      "members": [
        "<DocumentReference object>"
      ],
      "admins": [
        "<DocumentReference object>"
      ]
    }
  }
}

Debug output

Errors in the JavaScript console: NIL

Output from firebase.database().enableLogging(true);: N.A.

Screenshots: N.A.

Expected behavior

There should be the ability to add additional queries after a Firestore collection reference is created, something like below:

this.publicChatsCollection = this.afFs.collection('chats', query => query.where('visibility', '==', 'public');
this.recentChats$ = this.publicChatsCollection.where(/* ... */);

The current workaround would be to get the Firestore collection's ref property and invoke the where method:

// I haven't tried this yet! It might not work - the code below was manually typed out by hand on GitHub's editor
this.recentChats$ = this.publicChatsCollection.ref.where(/* ... */);

However, this loses on the benefits of AngularFire's observers.

Actual behavior

It is currently not possible to append additional queries to a collection reference.

jamesdaniels commented 3 years ago

Correct. You'll want to use RXJS operators to achieve this. I have an admittedly old example here https://stackblitz.com/edit/angularfire-db-api-fbad9p which should give you the gist of the solution