Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firebase / firestore docs queries Not working - javascript

As 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. In docs they have told this (i have used) way.

enter image description here

like image 321
Noman Ali Avatar asked Sep 12 '25 07:09

Noman Ali


2 Answers

It looks that tou want to call.data() on collection of documents, not one document. Please see if this code works:

db.collection("users").get().then(function(querySnapshot){
  querySnapshot.forEach(doc => {
     console.log(doc.data());
  });
}).catch(err => {
   console.log('Error getting documents', err);
});
like image 121
Andrzej Smyk Avatar answered Sep 13 '25 22:09

Andrzej Smyk


You should use docs.map then doc.data(). Here is how to do it with Firestore using async await syntax

import firebase from 'react-native-firebase'

async fetchTop() {
  const ref = firebase.firestore().collection('people')
  const snapshot = await ref.orderBy('point').limit(30).get()
  return snapshot.docs.map((doc) => {
    return doc.data()
  })
}
like image 33
onmyway133 Avatar answered Sep 13 '25 21:09

onmyway133