Home > front end >  Cloud Functions read one document from firestore
Cloud Functions read one document from firestore

Time:08-11

I'm trying to read a user document from firestore but everytime I try to run it, it crashes and gives me a different error. This is my code:

try {
        return await admin.firestore().collection('users').where("username", "==", id).get().then(snapshot => {
            var user;
            snapshot.forEach(doc => {
                user = {
                    "displayName":doc.data().displayName,
                    "photoURL": doc.data().photoURL,
                    "username": doc.data().username,
                    "bio": doc.data().bio
                }
            })
            return user;
        }).catch(err => {
            warn(err);
            return { displayName: "user", photoURL: "https://nonicapp.web.app/assets/logo/1.png", username: id, bio: "" };
        })
    } catch (err) {
        warn(err);
        return { displayName: "user", photoURL: "https://nonicapp.web.app/assets/logo/1.png", username: id, bio: "" };
    }

Las run it came up with this error: (intermediate value).then is not a function

How can I get my users profile info? Thank you

CodePudding user response:

admin.firestore().collection('users').where("username", "==", id).get()

returns a promise and there are two ways to handle promises: async/await or then/catch. Using both can cause errors.

Using async/await:

try {
    const snapshot = await admin.firestore().collection('users').where("username", "==", id).get()
    var user;
    snapshot.forEach(doc => {
        user = {
            "displayName":doc.data().displayName,
            "photoURL": doc.data().photoURL,
            "username": doc.data().username,
            "bio": doc.data().bio
        }
    })
    return user;
} catch (err) {
    warn(err);
    return { displayName: "user", photoURL: "https://nonicapp.web.app/assets/logo/1.png", username: id, bio: "" };
}
  • Related