1

I have a problem, here is the code:

        const firstName = "rick";

        const users = await db.collection('user');

        if (firstName != undefined) {
            users.where("name", "==", firstName );
        }
        
        const snap = users.get();

why this query return me the whole document with all objects? How to do a query based on where clause that can be null or undefined? Thanks for any help!

markWanka
  • 704
  • 1
  • 12
  • 29

1 Answers1

2

You are not reassigning the users and hence it's fetching whole collection. Try refactoring like this:

let users: firebase.firestore.Query = db.collection('user'); 
//^ let instead of const

if (firstName) { 
  users = users.where("name", "==", firstName );
  // ^^ updating original 'users' value
}
        
const snap = users.get();
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84