我想将数据从 /api/firestore/read.js 传递到 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);
});
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,
};
返回此数据的正确方法是什么?
这就是答案:`
只需对 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,
};