'res.json returns undefined from express server after retrieving data from firebase realtime database

I currently have a realtime database set up that saves a list of a specific user's list of saved jobs for a job search application with react on the front end. However, when I try to return that data through res.json, console.logging it prints out undefined. Would appreciate any help or insight on why it is behaving this way and/or possible fixes. Thanks in advance.

The data looks something like this:

{
  "users" : {
    "<userId>" : {
      "savedJobs" : [ {
        "company" : "PepsiCo",
        "id" : 7693578,
        "location" : [ {
          "name" : "Valhalla, NY"
        } ]
      } ]
    }
  }
}

It is initialized like so:

var admin = require("firebase-admin");

let db = admin.database();
var userRef = db.ref("users");

Old Backend logic:

app.get("/fetchSavedJobs/:userId", (req, res) => {
  console.log("inside fetch saved jobs");
  console.log("fetch saved jobs user id " + req.params.userId);
  const userId = req.params.userId;
  let list = [];
 
   userRef.orderByChild(userId).limitToLast(1).once('value').then((querySnapshot) => {
    if(!querySnapshot.numChildren) {
      throw new Error("user not in database, no saved jobs");
    }
    let dataSnapshot; 

    querySnapshot.forEach((snap) => {
      dataSnapshot = snap;
    })
    if (!dataSnapshot.exists()) { // value may be null, meaning idToFind doesn't exist
      throw new Error(`Entry ${userId} not found.`);
    }
 
    
    const jobsList = dataSnapshot.val().savedJobs;
    
    jobsList.forEach((x) => list.push({company: x.company, id: x.id}));

    return res.json(list);
    
  })

I've re-edited my back-end to to the following:

console.log(userId, typeof userId) prints "userId_value, string"

app.get("/fetchSavedJobs/:userId", (req, res) => {
  
  const userId = req.params.userId;
  var userRef = db.ref("users/" + userId);  //initializing userRef
  let list = [];

  userRef.once("value").then((snapshot) => {
    console.log("snapshot val", snapshot.val());
    res.json(snapshot.val().savedJobs);
  })

Front end:

export const fetchSavedJobs = (userUid) => {
  return async (dispatch) => {

    const fetchData = async () => {
        console.log("fetch data is called");
      
        const response = await fetch("/fetchSavedJobs/" + userUid, {
            method: "GET",
            headers: {
              'Accept': 'application/json',
              "Content-Type": "application/json",
            },
          });

      if (!response.ok) {
        throw new Error("Fetching saved cart data failed");
      }
    };

    try {
      const savedJobsData = await fetchData();
      console.log("came back from server with saved jobs");
      console.log("retrieved Saved Jobs data" + savedJobsData); //this prints out undefined
  
    } catch (error) {}
  };
};


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source