Reputation: 11
this is the code: the collection name is"usernames" and documents have a field known as "userName" and i am limitting the data retrieved to 1. i have exactly one document that matches the query and using console logs i verified that data is being retrieved but still everytime snapshot.exists gives me an undefined
db.collection("usernames").where("userName", "==", userName.toString()).limit(1).get()
.then(snapshot => {
if(snapshot.exists)
window.alert("Username already exists");
else{
window.alert("Username added");
db.collection("usernames").add({
profilePic: "",
userName: userName
})
db.collection("users").add({
age: age,
email: email,
firstName: fname,
lastName: lname,
mobileNo: mobileNo,
password: password,
userName: userName
})
.then( user => dispatch(addNewUser(user)))
.catch(error => dispatch(addUserFailed(error)));
}
})
.catch(error => dispatch(addUserFailed(error)));
snapshot.exists always is undefined even though the documents are read
Upvotes: 1
Views: 611
Reputation: 317412
In your code, snapshot
is a QuerySnapshot object, which is a container for 0 or more DocumentSnapshot objects resulting from the query. The linked API documentation suggests that there is no attribute "exists" on a QuerySnapshot. Only DocumentSnapshot has an exists property, but that's not what you have here.
Even if you are expecting exactly one document from the query, you still should check the QuerySnapshot to make sure it contains the one document you're looking for. You could do this by checking the size() of the results:
.then(querySnapshot => {
if (querySnapshot.size() > 0) {
const docSnapshot = querySnapshot.docs[0];
}
else {
// decide what you want to do if no results
}
Upvotes: 2