Query for an established user's username

I am trying to get the username of a user based on their uid in the following firebase structure:


I think I am able to get the user document but not the specific username value with the following line:

var username = this.afs.collection('users', ref => ref.where('uid', '==', uid)).valueChanges()

I am using the query documentation from AngularFire2:

1 Like

You’re actually getting the document whose uid == uid. To get the value of the uid itself, try this.

let userReference: AngularFirestoreCollection<{}> = this.afs.collection('users', ref => ref.where('uid', '==', uid));
let user$: Observable<{}> = userReference.valueChanges();
let userSubscription: Subscription = user$.subscribe(data => {

This should get you what you’re looking for. You should see the entire user object in console.log. The typing: i.e., user$: Observable<{}> <-- is not necessary, but a good idea, and definitely something to look into. The next step would be making a User interface to attach to



Though, this method of querying is / seems best suited for getting multiple results.
Something like this might be better for when you’re just looking to get one specific user

getUser(uid: string){
    let user: User;
    let userKey = this.fireStore.collection<User>('users', ref => ref.where('uid', '==', uid)).ref.id;
    let user$: Observable<User> = this.fireStore.collection<User>('users').doc(userKey).valueChanges() as Observable<User>;
    let userSub: Subscription = user$.subscribe(data => {
    user = data;

Not sure if these methods fit best-practices for Firestore (if best-practices have been determined yet), so take it with a grain of salt

1 Like

this was helpful, thanks! the first option gave me data where I could access username with

No problem. This might work even better for you.

let userRef = this.afs.collection('users').ref.where('uid', '==', uid);
userRef.get().then((result) => {
  result.forEach(doc => {
   //added benefit of getting the document id / key

The second option I had posted earlier, I now realize is not effective.
This approach is more along the lines of a simple query, as opposed to Observing and Subscribing, etc.

1 Like

You are correct. I also just discovered that your first option works with the localhost web app but doesn’t compile when pushed to ionic master. But this third option works great on localhost and compiles fine too. I should note I was able to access a value username with doc.data()['username'] instead of doc.username. Thanks a bunch!

1 Like

———- Happy to help ————

1 Like

Thank you for your help!