Noman Ali
Noman Ali

Reputation: 3340

Cloud Firestore collections queries not working

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

Upvotes: 11

Views: 11209

Answers (1)

Dan McGrath
Dan McGrath

Reputation: 42008

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);
});

Upvotes: 13

Related Questions