1

When I user registers I upload their username and email to the a firestore collection as a unique document. I want a code which checks if the username and the email is in the firestore database and if it isn't then the registration is successful otherwise it isn't.

So far this is my code but with this method if I start spamming the register button then the user's data gets added to the firestore database as many times as i pressed the button which results in documents with duplicate usernames and emails.

submit() {
    if (!this.signUpForm.valid) {
      return;
    }

    let data =
    {
      'bio': "not set",
      'completedList': new Array<string>,
      'dislikedList': new Array<string>,
      'email': this.signUpForm.value.email,
      'isBanned': false,
      'likedList': new Array<string>,
      'planList': new Array<string>,
      'username': this.signUpForm.value.name
    };

    this.afs.collection('user').add(data);

    const { name, email, password } = this.signUpForm.value;
    this.authService.signUp(name as string, email as string, password as string).pipe(
      this.toast.observe({
        success: 'Regisztráció sikeres!',
        loading: 'Bejelentkezés...',
        error: ({ message }) => `${message}`
      })
    ).subscribe(() => {
      this.authService.sendEmail(); // Send verification email
      this.authService.logout();
      this.router.navigate(['/auth'])
    })
  }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Pat Rose
  • 13
  • 3
  • To enforce uniqueness on Firestore you will need to use the value that you want to be unique (username in your case) as the ID of a document. This has been covered a few times before, so I linked some of the top answers to yours - but also see: https://stackoverflow.com/search?q=%5Bgoogle-cloud-firestore%5D+unique+username – Frank van Puffelen Mar 08 '23 at 15:12

0 Answers0