0

I want to pass data from /api/firestore/read.js to mainServer.js.

It does have the document, it prints, but does not return the data.

mainServer.js

app.get("/api/profile", async (req, res) => {
  const uid = req.user.uid;
  const userReader = new usersReader(uid);
  const data = await userReader.readData();
  console.log("Data", data); // data is undefined
  res.status(200).send(data);
});

read.js

const admin = require("../../firebase-config").admin;
class ReadFireDb {
  constructor(_uid) {
    this.uid = _uid;
  }

  async readData() {
    await admin
      .firestore()
      .collection("users")
      .doc(this.uid)
      .get()
      .then((snapShot) => {
        if (snapShot.exists) {
          console.log(snapShot.data()); // here i print data correctly
          return snapShot.data(); // here is the problem
        } else {
          return null;
        }
      })
      .catch((err) => console.log(err));
  }
}

module.exports = {
  ReadFireDb,
};

how is the correct way to return this data?

Maya Rahto
  • 49
  • 1
  • 5

1 Answers1

0

This is the answer:`

Just make some changes to read.js

const admin = require("../../firebase-config").admin;
class ReadFireDb {
  data;
  constructor(_uid) {
    this.uid = _uid;
  }

  async readData() {
    await admin
      .firestore()
      .collection("users")
      .doc(this.uid)
      .get()
      .then((snapShot) => {
        if (snapShot.exists) this.data = snapShot.data();
      })

      .catch((err) => console.log(err));
    return this.data;
  }
}

module.exports = {
  ReadFireDb,
};
Maya Rahto
  • 49
  • 1
  • 5