Ranindu
Ranindu

Reputation: 1063

How to read specific collection in firebase?

I have two components to login as an 'User' and 'Worker'.Their data s in two collection name as 'users','workers'.This is my 'User Login' function.

SignIn(email, password) {
    this.value = this.afs.collection( 'users'  , ref =>
      ref.where('email', '==', email)
    ).valueChanges();
    this.value.subscribe(data => {
      this.datas = data;
      console.log(this.datas )
        return this.afAuth.auth.signInWithEmailAndPassword(email, password).then((result) => {
          this.ngZone.run(() => {
            this.router.navigate(['home']);
          });
        }).catch((error) => {
          window.alert(error);
          this.router.navigateByUrl('signinu');
        })
    });
  }

So in this function i can login with using 'workers' collection data.That's mean 'Worker' can login with 'User login'component. So how to fix this? please help me.

This is my 'worker login' function

SignIn(email, password) {
        this.value = this.afs.collection('workers', ref =>
            ref.where('email', '==', email)
        ).valueChanges();
        this.value.subscribe(data => {
            this.datas = data;
            console.log(this.datas)
            if (this.datas !== null) {
                return this.afAuth.auth.signInWithEmailAndPassword(email, password).then((result) => {
                    this.ngZone.run(() => {
                        this.router.navigate(['/profile/' + this.datas[0].uid]);
                    });
                }).catch((error) => {
                    window.alert(error);
                    this.router.navigateByUrl('signinu');
                })
            } else {
                window.alert('Invalid user');
            }
        });
    }

Upvotes: 0

Views: 99

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

In the sign in page, create a dropdown menu where the user can choose if he is a user or worker, then in the signin method add another parameter called type:

SignIn(email, password, type)

And check if type is equal to user then use collection user else if type is equal to worker then use collection worker. When you are retrieving you are already using the where to query if the email exists in the user collection or the worker collection. If a user is worker and they clicked on user, then since you are doing a query to check the email nothing will be retrieved and you can show an alert.

Upvotes: 1

Related Questions