skip to Main Content

I have a collection "user" and the document ID of the user is different from the current user’s UID. So when I use FirebaseAuth.instance.currentUser!.uid in the following code it doesn’t work. I am using anonymous login to create users not sure if this makes a difference.

FirebaseFirestore.instance.collection('user').doc(FirebaseAuth.instance.currentUser!.uid).collection('subcollection')

Document ID

enter image description here

UID

enter image description here

Would really appreciate it, if someone could clarify:

  • If this is normal Firebase behavior make docid and uid different.
  • How to access current user’s data in this scenario.
  • How to make both the document ID and uid the same.

2

Answers


  1. Chosen as BEST ANSWER

    The following code creates the user document with UID as it's name.

    try {
    // Logs in the user anonymously
    final userCredential = await FirebaseAuth.instance.signInAnonymously();
    
    // Gets the UID
    String uid = userCredential.user!.uid;
    
    // Creates a field inside the user document to store the UID
    final userData = {"UID": uid, };
    
    // Creates the user document with the UID as it's name
    await FirebaseFirestore.instance.collection('user').doc(uid).set(userData);
    
    print("Signed in with temporary account.");
      } on FirebaseAuthException catch (e) {
        switch (e.code) {
          case "operation-not-allowed":
            print("Anonymous auth hasn't been enabled for this project.");
            break;
          default:
            print("Unknown error.");
        }
      }
    

  2. The FirebaseAuth.instance.currentUser!.uid returns:

    The user’s unique ID.

    And to answer your questions.

    If this is normal Firebase behavior to make docid and uid different.

    No, it’s not. If you write a document to Firestore when the authentication is successful using the following document reference:

    FirebaseFirestore.instance.collection('user').doc(FirebaseAuth.instance.currentUser!.uid)
    

    You’ll end up having a document in Firestore that has the same document ID as the UID that comes from the authentication process.

    How do I access the current user’s data in this scenario?

    Exactly as already do, using FirebaseAuth.instance.currentUser!.uid.

    How do we make both the document ID and UID the same?

    Using the above document reference and calling the DocumentReference#set() function, but only when the authentication is successful. Please also notice, that if you sign the user out and sign in anonymously again, a new UID is generated. There is no way you can use an old anonymous UID.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search