Reputation: 488
I'm using React and Firebase to create a small app. I'm trying to check for a document related to users in my firestore database where the document ID is the same as the uid generated by firebase auth, but for some reasons the .get() promise stays as pending, causing the .exists() function to throw an error (TypeError: userDoc.exists is not a function). I initially thought it was a problem with my db rules, so I changed them so anyone could read and write to the database (not secure I know, the rules will be changed later).
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Even after this, I still cannot retrieve the document. Below is my code.
let userDoc = db.collection('Users').doc(currentUser.uid)
console.log(userDoc);
userDoc = userDoc.get();
console.log(userDoc);
userDoc = userDoc.exists();
db is a Firestore object created using
admin.initializeApp()
db = admin.firestore()
and let userDoc = db.collection('Users').doc(currentUser.uid)
results in a DocumentReference object. The document exists in firestore, but I just for some reason cannot access it in my react app. I've written a cloud function also working with firestore, and it has has had no problem reading and writing to my db. I feel like I'm missing something here and would really appreciate any help.
Upvotes: 0
Views: 1572
Reputation: 699
userDoc = userDoc.get();
In this line userDoc.get()
returns a promise and assigns to userDoc
. When that promise is resolved- you will receive a DocumentSnapshot which would then have the exists
property.
userDoc.get()
.then(doc=> {
if(doc.exists) console.log(doc.data());
})
You can look at the examples in the documentation as to how to read data using javascript sdks.
Upvotes: 1
Reputation: 58593
userDoc.get();
is promise
, and it's making a request via .get()
so it will be on pending state.
And change exists()
to exists
. REF
userDoc.get().then(data => {
console.log(data , data.exists); //<--- Try to check here
});
console.log(userDoc); // <--- this will give you Promise with pending state
OR you can use async await
:
async function getData() { // <------ async
let userDoc = db.collection('Users').doc(currentUser.uid)
console.log(userDoc);
userDoc = await userDoc.get(); // <------ await
console.log(userDoc);
userDoc = userDoc.exists; // <------ exists not exists();
}
Upvotes: 2