Cloud Firestore collections queries not working

10,590

I think you have some things confused as querySnapshot doesn't have data, but it does have docs which have data.

In your first example, you are asking it to return all documents in the collection. You'll want something like this instead:

db.collection("users").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        console.log(doc.id, " => ", doc.data());
    });
});

Key difference is looping over the docs in querySnapshot and console logging the data from each doc.

For your second example, you'll want to check if the querySnapshot is empty, rather than checking if it exists.

db.collection("users").where("mobile_no", "==", mobileToCheck)
.get()
.then(function(querySnapshot) {
    if (querySnapshot.exists) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, " => ", doc.data());
            var userData = doc.data()
            var userId = doc.id
            console.log(mobileToCheck + "Exist In DB");
        });
    } else {
        console.log(mobileToCheck + "Do Not Exist In DB");
    };
})
.catch(function(error) {
    console.log("Error getting documents: ", error);
});
Share:
10,590

Related videos on Youtube

Noman Ali
Author by

Noman Ali

BY DAY: I am a professional full stack web developer at an IT Company, and love to do creative front end and backend apps. BY NIGHT: I am a movie/drama lover. And play games whenever i get some extra time.

Updated on July 09, 2022

Comments

  • Noman Ali
    Noman Ali almost 2 years

    As Cloud Firestore is new, I am having problems using it.

    I have to get Collection of all users and traverse it. But it is not working.

    db.collection("users").get().then(function(querySnapshot){
          console.log(querySnapshot.data());
    });
    

    It says:

    querySnapshot.data is not a function

    And following code:

    callFireBase(mobileToCheck){
            db.collection("users").where("mobile_no", '==', mobileToCheck).get().then(function(querySnapshot){
                if (querySnapshot.exists) {
                    var userData = querySnapshot.data();
                    var userId = querySnapshot.id;
                    console.log(mobileToCheck + "Exist In DB");
                }else{
                    console.log(mobileToCheck + "Do Not Exist In DB");
                }
            });
    }
    

    Is always printing

    923052273575 Do Not Exist In DB

    Even if it exists, See following image for reference.

    enter image description here

  • Lahari Areti
    Lahari Areti almost 6 years
    @ Dan McGrath I have used the above query But for me it always says user does not exist. But number is in database . Whats the problem