Johannes Beier
Johannes Beier

Reputation: 15

Firestore Request, check if doc exists

I am struggling for a while now with this Firestore check.

let currentUser = firebase.auth().currentUser;

console.log(currentUser.uid);
let docRef = db.collection("StartNumbers").where('UserId', '==', currentUser.uid);
docRef.get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            if (doc.exists){
                console.log('document exists')
                chooseMode.style.display = 'grid';
                onlinePopout.style.display = 'none';
                console.log('user is logged in');   
            } else { 
                console.log('no such document');
                nameOuter.style.display = 'grid';
            }
        });    
}).catch ((err) => {
    console.log("Error getting document:", err)
})   

If doc exists, everything works fine. If there is no such document nothing happens, no error message, no console.log...

Can you help me finding my mistake?

Upvotes: 1

Views: 578

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50930

Queries will returns documents which exactly match your condition and that essentially means all the documents returned in a QuerySnapshot exist. Therefore, it's redundant to add that if (doc.exists) check in a forEach loop.

If there is no such document, nothing happens.

You should use .empty property on the QuerySnapshot itself to check if your query returned any matched documents like this:

let docRef = db.collection("StartNumbers").where('UserId', '==', currentUser.uid);
docRef.get().then((querySnapshot) => {
  if (querySnapshot.empty) {
    console.log("NO documents matched the condition")
  } else {
    console.log(querySnapshot.docs.map(doc => doc.data()))
    // proceed with adding HTML elements here
  }
})

Upvotes: 2

Related Questions