1

Firestore database

Given the following data struct in firebase, I wish to retrieve the field in just standard JS. I have tried many methods of getting it, but for some reason, I cannot. I have tried .get(), forEach(), I have tried getting a snapshop, but it won't work. At the start of my JS file I do:

const auth = firebase.auth();
const db = firebase.firestore();

let totalGroups;
db.collection('totalGroups').doc('totalGroups').get().then(function(querySnapshot) {
    querySnapshot.docs.forEach(function(doc) {
        if (doc.data().totalGroups != null) {
            totalGroups = doc.data().totalGroups console.log("here is total groups" + totalGroups)
            //Total Groups is undefined out here but defined in fuction
        }
    })
})

and normally I am able to get .get() just fine. I am looking for the most simple method of getting this value. thanks.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
sdfasdf
  • 11
  • 1
  • Can you share the code that you've tried? The `get()` part that you are saying is not working. – Dharmaraj Jan 13 '22 at 05:47
  • @Dharmaraj let totalGroups; db.collection('totalGroups').doc('totalGroups').get().then(function (querySnapshot) { querySnapshot.docs.forEach(function (doc) { if(doc.data().totalGroups != null){ totalGroups = doc.data().totalGroups console.log("here is total groups" + totalGroups) } } //Total Groups is undefined out here but defined in fuction – sdfasdf Jan 13 '22 at 05:53

1 Answers1

0

First, you are using get() on a DocumentReference which returns a DocumentSnapshot containing data of that single document only and has no docs property on it. Try refactoring the code as shown below:

db.collection('totalGroups').doc('totalGroups').get().then(function(snapshot) {
    const docData = snapshot.data();
    console.log(docData)
})

Also do note that if you were using get() on a CollectionReference, then it would have returned a QuerySnapshot where the existing code works fine.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • Thank for for the helpful info, but I still get undefined when I console.log outside the function – sdfasdf Jan 13 '22 at 06:22
  • @sdfasdf that is the intended behavior. Read more about this here: [How to get data from Firestore DB in outside of onSnapshot?](https://stackoverflow.com/questions/52488087/how-to-get-data-from-firestore-db-in-outside-of-onsnapshot) – Dharmaraj Jan 13 '22 at 06:25