Get value from Firebase using javascript

Viewed 95

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

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

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.

Related