Home > Software engineering >  How to make a field of a document a primary key in firebase
How to make a field of a document a primary key in firebase

Time:11-11

So I want to prevent a document with same email field to get added into the firestore database.This is automatic in authentication but not in firestore.

This is my base function:

const register = async () => {
        await addDoc(userCollectionRef, {username: userName, email: newUser, password: registerPassword})
        try {
          const user = await createUserWithEmailAndPassword(auth, newUser, registerPassword);
          console.log(user);
        } 
        catch(e) {
          console.log(e.message);
          console.log(e.code);
          if((e.code) === "auth/email-already-in-use"){
            window.alert("Email already registered");
          }
        }
        
    }

What should i do to make email field a primary key?

CodePudding user response:

Firestore doesn't have the concept of a primary key. The closest equivalent is the document ID.

If you want to specify your own document ID, use setDoc with a document reference instead of addDoc:

const userDocRef = doc(userCollectionRef, newUser)
await setDoc(docRef, {username: userName, email: newUser, password: registerPassword})

Also see the Firebase documentation on writing a document.

CodePudding user response:

You should write in firebase after creating a user with email and password.

const register = async () => {
        
        try {
          const user = await createUserWithEmailAndPassword(auth, newUser, registerPassword).then(() => await addDoc(userCollectionRef, {username: userName, email: newUser, password: registerPassword})) ;
          console.log(user);
        } 
        catch(e) {
          console.log(e.message);
          console.log(e.code);
          if((e.code) === "auth/email-already-in-use"){
            window.alert("Email already registered");
          }
        }
        
    }

As Frank mentioned above, there is no way, to achieve your purpose, you can make use of the Firebase createUser function in the sdk. If the user is already created, it will throw an error, and your write document to firebase will not be triggered.

  • Related