Q:

Check if displayName in users is unique Firebase & Angular

Just before adding a new user to firebase, I want to check if the displayName already exists for an other user. I'm storing the displayName in users:
root / users / document *(uid as id)* / fields *like uid, displayName, email, ...*

I've tried it like this:
import { Injectable, NgZone } from '@angular/core';
import { auth } from 'firebase/app';
import { User } from "./user";
import { Router } from "@angular/router";
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { AngularFireDatabase } from '@angular/fire/database';
import { ToastController } from '@ionic/angular';

...

constructor(
    public firestore: AngularFirestore,
    public firebase: AngularFireDatabase,
    public ngFireAuth: AngularFireAuth,
    public router: Router,
    public ngZone: NgZone,
    public toastController: ToastController
  ) {
    this.getUserData();
    this.newUser = {} as newUser;
  }

...

  check_displayName() {
    var usersRef = this.firestore.collection("users");
    usersRef.where(doc.forEach(doc => doc, '==', this.state.displayName)).get()
      .then(snapshot => {
        if (snapshot.empty) {
              console.log('displayName is unique', snapshot.empty)
              return false
        } else {
              return true
              console.log('displayName already exists')
        }
      })
  }

But I get an issue:

ReferenceError: doc is not defined

How can I iterate through the docs when there are unique document-ids (uid)?
Thx for your hints

A:

Can you try this ??
check_displayName(userNameToCheck) {
    const usersRef = this.afStore.collection("users");
    usersRef.where('displayName', '==', userNameToCheck).get()
        .then(snapshot => {
            if (snapshot.empty) {
                console.log('displayName is unique', snapshot.empty);
                return false;
            } else {
                console.log('displayName already exists');
                return true;
            }
        });
}

I think you need to get the snapshot first and check if it is empty. There is no meaning in iterating through all docs and increasing your Firestore Reads.
And regarding the forEach(), first you need to get the snapshot and then use something like snapshot.forEach(). But in your case, if the snapshot is empty the username is unique and you did you job with just 1 read cost.
Small Tip: I have not checked if username comparision is case-sensitive. So I keep another field named displayNameLower and then compare that with lower-cased version of username to check.
Something like; .where('displayNameLower', '==', userNameToCheck.toLowerCase())

