Dalon
Dalon

Reputation: 700

How to get the current UserId from Firestore?

I have a collection users where every user has his own document. Now I want to create a subcollection to store more data related to a specific user.

This is the code so far:

class DatabaseService {

  Future isUserRegistered(String uid) async{
    return await FirebaseFirestore.instance.collection('users')
        .where('uid', isEqualTo: uid)
        .get();
  }

  Future registerNewUser(email, password, uid) async{
    return await FirebaseFirestore.instance.collection('users')
        .doc(uid).set(
      {
        "email": email,
        "password": password,
        "uid": uid,
        "token": -1,
        "userGoal": false,
        "userGender": false,
      },
    );
  }

I created a save function but instead of storing data in a subcollection within the document with the current uid, firestore creates a new document named 'uid'. How to fix that?

  Future saveInSubcollectionToRemote() async{
    Map<String, dynamic> data = UserManager.userWeights;
    return await FirebaseFirestore.instance.collection('users')
        .doc('uid')
        .collection('weights')
        .doc(data['userWeight'])
        .set(data);
  }

class UserManager {
  static Map<String, dynamic> userWeights = {'weights': []};
}

EDIT This is my google authentication, here i get an id but instead of this id i want the uid

  ///Authentication

  void signInGoogle(context) {
    DatabaseService handler = new DatabaseService();
    _googleSignIn
        .signIn()
        .then((userdata) => {
              print(userdata.toString()),
              handler
                  .isUserRegistered(userdata.id.toString())
                  .then((value) => {
                        if (value.docs.length == 0)
                          {
                            print("Not registered"),
                            registerUserToApp(
                                context, userdata.email.toString(), "password", userdata.id.toString())
                          }
                        else
                          {
                            print(value.docs[0].data().toString()),
                            UserManager.userdata = value.docs[0].data(),
                            Navigator.pushAndRemoveUntil(
                              context,
                              MaterialPageRoute(
                                builder: (context) {
                                  return NavBar();
                                },
                              ),
                              (route) => false,
                            ),
                          }
                      })
                  .catchError((e) => {
                        showAlertDialog(
                            context, "Error", ""),
                      })
            })
        .catchError(
            (e) => {showAlertDialog(context, "Error", "")});
  }

  void registerUserToApp(context, email, password, uid) {
    DatabaseService handler = new DatabaseService();
    try {
      handler.registerNewUser(email, password, uid).then((value) => {
            showAlertDialog(context, "Congratulations!",
                "You registered to the app"),
          });
    } catch (error) {
      print(error.toString());
      showAlertDialog(context, "Error", "");
    }
  }
}

Upvotes: 0

Views: 2371

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598887

The uid in your code is typically the unique identified of the user. Firestore itself has no knowledge of such a uid. Instead, the uid comes from the identity provider that you use.

You could use the user ID from Google Sign-in to identify the user in Firestore, but it's more common to sign in with Firebase (too).

Once you've signed in to Google, you can use those credentials to sign in to Firebase Authentication by calling signInWithCredential as shown in the documentation on social authentication.

Once you're signed in to Firebase Authentication you'll get a UID from Firebase Authentication, which you can then use to identify the user's documents in Firestore (and later also secure access to those documents).

Once you've done that, you can get the current user (and from there their UID) through FirebaseAuth.instance.currentUser (once) or FirebaseAuth.instance.currentUser() (continuous) and then again use that in your Firestore calls.

Upvotes: 2

Mozes Ong
Mozes Ong

Reputation: 1294

Using doc('uid') is setting your document id as 'uid'. This is whats causing your issue.

Try this:

  Future saveInSubcollectionToRemote(String uid) async{
    Map<String, dynamic> data = UserManager.userWeights;
    return await FirebaseFirestore.instance.collection('users')
        .doc(uid)
        .collection('weights')
        .doc(data['userWeight'])
        .set(data);
  }

pass in uid like you did in registerNewUser()

Upvotes: 0

Related Questions