简体   繁体   中英

How to create user collection with uid in firestore?

I'm trying to create a user collection in firestore as in following order.

Users>> user.uid >> data but my code is not working. my code

firestore()
    .collection('Users')
    // .add(`${data.uid}/${data}`)
    .doc(`${data.uid}`)
    .set(data)
    .then(() => {
      console.log('User added!');
    });

this is data variable

{"name": "John", "uid": "g1YWGe0zkzRgVvOEyI43eBbpwbT2"}

This did it for me you can checkout

firebase.firestore().collection("Users")
      .doc(data.uid).set(data)
      .then(result => {

       console.log('User added!');
       
       });

You can get the current user id and place it inside your addUser function like this:

FirebaseAuth auth = FirebaseAuth.instance;
final userId;

if (auth.currentUser != null) {
  print(auth.currentUser.uid);
  userId = auth.currentUser.uid;
}

Place the user id inside your user function

Future<void> addUser(userId) {
      // Call the user's CollectionReference to add a new user
      return users
          .add({
            'full_name': fullName, // John Doe
            'company': company, // Stokes and Sons
            'age': age // 42
            'uid': userId
          })
          .then((value) => print("User Added"))
          .catchError((error) => print("Failed to add user: $error"));
    }

Firestore doc: https://firebase.google.com/docs/firestore/quickstart

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM