简体   繁体   中英

Firebase Querying?

I have an issue querying in my firebase database. I am trying to get all data of an authenticated user from my endpoint ".../api/user". This is the route in my code:

// GET DATA OF USER
router.route("/user").get(FBAuth, getAuthenticatedUser);

Here I use a middleware which decodes the token and sets it in the req.user, and of course verifies if the user is authenticated:

// 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);
        });
    };

All the above works fine, but after the req.user set successfully, we go to the function "getAuthenticatedUser" which doesn't work:

//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 });
        });
    };

I don't see how the query can work for the logging, for the middleware but not for the actual controller which must use this setup before cause it is a private route?

I finally fixed it, if anyone has the same issue here is the solution:

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 });
        });
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM