0

I´m creating profiles for signed in users. The problem that I´m having is that under some circumstances is allowing to create duplicate profiles for a given uid instead of returning the one that already exists.

const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
    if (user) {
        findProfile(user.uid)
            .then((profile) => console.log(profile))
            .catch((error) => createProfile(user.uid))
    } else {
        console.log("user not signed in")
    }
});

export const findProfile = (uid) => {
    return firebase
        .collection("profiles")
        .where("uid", "==", uid)
        .get()
        .then((querySnapshot) => {
            if (querySnapshot.size > 0) {
                return querySnapshot.docs[0];
            } else {
                throw new Error("profile not found");
            }
        });
};

export const createProfile = (uid) => {
    return firebase.collection("profiles").add({uid});
};
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
handsome
  • 2,335
  • 7
  • 45
  • 73

1 Answers1

1

Firebase Auth UIDs are unique. Given that they are unique, you can use it as the ID of your documents in "profiles" instead of accepting the random ID you get with add(). So, you should instead use set() and specify the UID in the path of the document to create. This will drastically simplify your code for both reading and writing.

firebase.collection("profiles").doc(uid).set({...})

Note that set() will fail like this if the document already exists, so you should check that as well.

Getting the document is then just:

firebase.collection("profiles").doc(uid).get()
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • it totally makes sense but unfortunately right now I have thousands of profiles with the random id you mentioned. need to find out a way to fix the duplicate issue. – handsome Oct 27 '20 at 18:21