Firebase查询?"/>
Firebase查询?
我在Firebase数据库中查询时遇到问题。我正在尝试从端点“ ... / api / user”获取经过身份验证的用户的所有数据。这是我的代码中的路线:
// GET DATA OF USER
router.route("/user").get(FBAuth, getAuthenticatedUser);
这里我使用中间件来对令牌进行解码并将其设置在req.user中,当然还要验证用户是否已通过身份验证:
// FBAuth middleware
module.exports = (req, res, next) => {
admin
.auth()
.verifyIdToken(idToken)
.then((decodedToken) => {
req.user = decodedToken;
return db
.collectionGroup("users")
.where("idUser", "==", req.user.uid)
.limit(1)
.get();
})
.then((data) => {
req.user.name = data.docs[0].data().name
return next();
})
.catch((err) => {
console.error("Error while verifying token", err);
return res.status(403).json(err);
});
};
以上所有方法都可以正常工作,但是在成功设置req.user之后,我们转到“ getAuthenticatedUser”函数不起作用:
//Controller
exports.getAuthenticatedUser = (req, res) => {
let userData = {};
db.collectionGroup("users")
.where("email", "==", req.user.email) //".where("idUser", "==", req.user.uid)" nothing works here
.limit(1)
.get()
.then((doc) => {
if (doc.exists) { // Always goes to the else no matter what query i do
userData.credentials = doc.data();
return db
.collection("comptes")
.doc(req.user.name)
.collection("courses")
.get();
}else{
return res.status(400).json({email: 'Email not found => ' + req.user.email});
// the req.user.email does exist and contain the right email, and also exists in the database...
}
})
.then((data) => {
if (data.exists) {
userData.courses= [];
data.forEach((doc) => {
userData.courses.push(doc.data());
});
}
return res.json(userData);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
};
我不知道查询如何用于日志记录,对于中间件,但对于实际的控制器却没有,因为必须使用此设置才能使用该设置,因为它是专用路由。谢谢您的帮助!
回答如下:我终于解决了这个问题,如果有人遇到相同的问题,这里就是解决方法:
exports.getAuthenticatedUser = (req, res) => {
let userData = {};
db.collectionGroup("users")
.where("email", "==", req.user.email)
.limit(1)
.get()
.then((doc) => {
if (doc.docs[0].exists) { // <----- doc.docs contain a list of data
userData.credentials = doc.docs[0].data();
return db
.collection("comptes")
.doc(req.user.name)
.collection("courses")
.get();
}
})
.then((data) => {
if (data.exists) {
userData.courses= [];
data.forEach((doc) => {
userData.courses.push(doc.data());
});
}
return res.json(userData);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
};
更多推荐
Firebase查询?
发布评论