简体   繁体   中英

How to add data to Firestore Cloud without hardcoding user collection document id in Swift

Initially I created a collection Users in my Firestore Cloud database with a subcollection Wishlist .

To add to the wishlist, I hardcoded the following to test it works:

      let db = Firestore.firestore()
            db.collection("users/JldiJEK5i84DZWhlTFg6/wishlist").addDocument(data: ["plant" : plants[0], "image" : plants[1]])
    } 

Once button is tapped, the plant is sent to that particular User's wishlist and it works -- I can see this being added to the database.

How do I... I cannot figure out in the documentation how not to hardcode the document id. I would like it to just add the plant for every user signed in?

Get the current user:

let user = Auth.auth.currentUser
if let user = user {
   _ = user.id
}

Then:

 let db = Firestore.firestore()
 db.collection("users/\(user?.uid ?? "error")").addDocument(data: ["plant" : plants[0], "image" : plants[1]])

This works for me when dealing with people/customers, I just have an error document in Firestore, but your user is more than likely never going to be nil if they log in or create an account.

Edit:

Just to be safe, this is probably better and will avoid unnecessary writes to Firestore when there's an error (saving money)

guard let currentUser = Auth.auth().currentUser {
    print("handle the error")
    return
}

let uid = currentUser.uid
...

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