简体   繁体   中英

Firebase Swift: How do I create a new collection using the UID under my “users” collection?

I am creating a new IOS app using Firebase Auth & Cloud Database. When a new user is added, a "profile" collection is created containing their initial sign up inputs. I need to figure out how to create a new collection under the "users" collection that uses the UID as its document id.

This is what I have coded so far for this bit, but I keep getting this message "Value of type 'CollectionReference' has no member 'child'" . I followed the Firebase instructions but I keep getting it wrong.

What am I missing?

        // Create the user
        Auth.auth().createUser(withEmail: email, password: password) { (result, err) in

            // Check for errors
            if err != nil {

                // There was an error
                self.showError("Error creating the user")
            }
            else {
                // User was created successfully, now store the first name and last name
                let db = Firestore.firestore()

                let uid = result!.user.uid


                //creates profile doc under uid with all the info
                db.collection("users").child(uid).addDocument("profile").setData([ "firstname":firstName, "lastname":lastName, "uid":uid, "companyname":companyName, "companyalias":companyAlias, "trucknumber":truckNumber, "trucktype":truckType]) { (error) in

                //db.collection("users").addDocument(data: ["firstname":firstName, "lastname":lastName, "uid":result!.user.uid ]) { (error) in

                    if error != nil {
                        //Show error message
                        self.showError("Error saving user data")
                    }
                }

                //Transition to home
                self.transitionToHome()
            }
        }
    }
}

I am concerned that I should probably create other collections in the beginning when a new user is created. I would need each user to have a "profile", "friends list" and "my jobs" collection all saved under the UID.

Should I worry much on whether to create all the required collections in the beginning?

As Frank van Puffelen mentioned. You could simply use the user data as your profile data then add subcollections as needed. No need to create subcollections when the user is created. In my example, subcollections are only created if the user utilizes other features of the app. I would add all of the different fields your user's profile needs and let them be modified by the user later but that is just my preference. 在此处输入图像描述

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