Search code examples
angularfirebasegoogle-cloud-firestoreangularfire

@angular/fire where exists


I'm getting a firestore's document with the 'where'.My goal is to know if this one already exists (like : is this pseudo in one collection) but with uid.

 var request = this.ms.afs.collection('users', ref => ref.where('uuidsocial', '==', uid)).get().subscribe(users => { 
      if(users.size > 0){
        console.log("exists");
        console.log(users.size);
      }else{
        console.log("doesn't exist");
      }
    });

Haven't worked, always returning 1, and I'm sure it's not the right code now, tried a lot of things. Thanks a lot


Solution

  • You can do it like this:

    var docRef = this.ms.afs.collection("users").doc(uid);
    docRef.get().then((doc) => {
        if (doc.exists) {
            console.log("Document data:", doc.data());
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
    

    See documentation here:

    https://firebase.google.com/docs/firestore/query-data/get-data

    Also do this with a query:

    this.ms.afs.collection('users', (ref) => ref.where('uuidsocial', '==',uid))
        .get()
        .subscribe(user => { if(user.size >= 0) ...do smthg })