Search code examples
javascriptangularfirebasegoogle-cloud-firestoreangularfire2

Returning UID in Firebase query


The following query below returns me a collection of data based on a user id. How do I do I make sure it returns the uid of each document in the query.

  getWebsitesByUserId(id) {
    return this.afs.collection('websites', ref => ref.where('createdBy', '==', id)).valueChanges();
  }

I understand that it involves something like this:

  return this.afs.collection('websites').doc(id).snapshotChanges().pipe(map(action => {
    const data = action.payload.data();
    const uid = action.payload.id;
    return {uid, ...data};
  }));

Just not sure how to implement in a query.


Solution

  • According to this pull request on the AngularFire Repo now there is an option that you can pass a string to the valueChanges method on a collection reference.

    This string will be the name of the property that will hold the IDs of the documents.

    For example:

    collectionRef.valueChanges('myIdKey').subscribe()
    

    Would emit:

    emits [ { myIdKey: 'MrfFpRBfWLTd7LqiTt9u', ...data }, ... ]
    

    So in your situation I guess it would be something like this:

     getWebsitesByUserId(id) {
        return this.afs.collection('websites', ref => ref.where('createdBy', '==', id)).valueChanges('uid');
      }