3

I tried to retrieve data with the following manner but it didn't work: Unhandled Rejection (TypeError): snapshot.val is not a function. (In 'snapshot.val()', 'snapshot.val' is undefined)

var companyScore, userScore;

            firebaseApp.firestore().collection('JobPosting')
            .doc(postId).get().then(snapshot => {
                console.log("Snapshot");
                console.log(snapshot);
                companyScore = snapshot.val().score;
              });
            firebaseApp.firestore().collection('people')
            .doc(currentUser.uid).get().then(snapshot => {
                userScore = snapshot.val().score;
              });

I guess I need a solution to get the snapshot data (supposedly a json or hash table), so that I can get the value under the index of score.

2 Answers 2

2

You should use .data() and not .val()

Therefore, the updated code will be like this:

var companyScore, userScore;

            firebaseApp.firestore().collection('JobPosting')
            .doc(postId).get().then(snapshot => {
                console.log("Snapshot");
                console.log(snapshot);
                companyScore = snapshot.data().score;
              });
            firebaseApp.firestore().collection('people')
            .doc(currentUser.uid).get().then(snapshot => {
                userScore = snapshot.data().score;
              });

Link to the official docs: https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document

Sign up to request clarification or add additional context in comments.

4 Comments

It worked partly, but I met a new issue: snapshot.data().score or snapshot.data()['score'] doesn't retrieve anything but NaN, though my firebase has already had the key score.
Try console.loging the data and see what are you getting
My fault there, buddy. I figured out that it's because of the asynchronized nature of firebase. thanks!
You're welcome buddy! Sometimes mistakes happen. I think you should go through the example codes given in the docs to refresh your knowledge about using the SDK.
0

Getting a document from Firestore returns a DocumentSnapshot which does not have a .val() method on it. (That method exists on Realtime Database's DataSnapshot).

Try refactoring your code to:

firebaseApp.firestore().collection('JobPosting').doc(postId).get().then(snapshot => {
  console.log("Snapshot", snapshot);
  companyScore = snapshot.data().score;
});

The data method:

Retrieves all fields in the document as an Object. Returns 'undefined' if the document doesn't exist.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.