I'm having trouble generating a random Unique ID using Cloud Firestore. Previously I was using the Realtime Database and to generate a random string I use the childByAutoID().key.
Is there a way of doing something similar for Cloud Firestore?
As Jay said in the comments this isn't a duplicate as I'm trying to generate a random string, I'm not trying to get random documents.
If you create the document without an explicit Id, our SDK will auto-generate a random one for you.
// Add a new document with a generated id.
var ref: DocumentReference? = nil
ref = db.collection("messages").addDocument(data: [
"sender": "<my_senders_id>",
"recipient": "<my_recipient_id>",
"message": "Hello from Google Cloud Platform & Firebase!",
"status": "unread"
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
To generate random id,
let ref = db.collection("somePath")
let docId = ref.document().documentID
Related
I;m new to firebase, I've users collection with documents, but the ID's are not know for me, I don't know how to access them, I tried with uid but those ID's doesn't look like uids therefore It didn't work
as you can see in the screenshot above, documents ids are different from users uids my target is to access user, after that document and add a new collection ( of course not in all users, the registered one.
any ideas how to access them?
// create user
Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
// check for errors
if let err = err {
// error occuried
showError("error while creating user")
}else {
// user was created succesfully,store name and vaccine
let db = Firestore.firestore()
db.collection("users").addDocument(data: ["username":self.usernameLabelRegister.text ,"vaccine":self.chosenVaccine,"nationality":self.chosenLocation, "uid":result!.user.uid,"profileImageUrl":RegisterViewController.staticProfileImageUrlString]) { error in
if error != nil {
// show error
showError("user data blablabla")
}
}
You are indeed adding a document with random ID (which is not same as user's UID). Instead use setData where you can specify the ID:
// Pass user ID from result of createUser
db.collection("users").document(result.user.uid).setData(data: ["username":self.usernameLabelRegister.text ,"vaccine":self.chosenVaccine,"nationality":self.chosenLocation, "uid":result!.user.uid,"profileImageUrl":RegisterViewController.staticProfileImageUrlString]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
Would it be possible to create documents in Firestore and then later reference it within swift/xcode/app? I want to manually add restaurant data into Firestore and then reference the data (city,type, phone number, etc.) within an app.
What do you recommend I do to be able to retrieve the manually typed out document entries?
Yes this is possible and not that hard to figure out when you look at the offical docs.
SDK IOS SETUP
https://firebase.google.com/docs/ios/setup
Getting started with firestorehttps://firebase.google.com/docs/firestore/quickstart#ios
Creating a new document in the collection "USERS"
// Add a new document with a generated ID
var ref: DocumentReference? = nil
ref = db.collection("users").addDocument(data: [
"first": "Ada",
"last": "Lovelace",
"born": 1815
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
Reading that data
db.collection("users").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}
For referencing documents made by users you could safe the UserID to the firestore document and filter the documents in the app by Current user ID.
This is mostly used in apps.
I would also suggest to watch some videos from:
https://peterfriese.dev/
This will give you a clear understanding on what to do with the data you get back.
let reference = Firestore
.firestore()
.collection(FBKeys.CollectionPath.users)
.document(uid)
reference.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document?.data()
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
I have created a cloud database using firebase. I have collection name is "users" and I have email, favoriteArtsts, name, uid as the fields. What I want to do is I want to add more artists to the favoriteArtsts array. However, to do so, I have to first get the reference to the array. By following the firebase instructions, I was able to get the user_id. The code above is the code I have tried. The code shows all the fields. However, I don't know how to get the favoriteArtsts values only. Is there a way to get the favoriteArtsts values?
You can get a single field by doing document.get("favoriteAritsts") (notice your typo in favoriteAritsts in your screenshots.
You can also do document.data()["favoriteAritsts"]
Both of the above will give you a return type of Any? so you would need to do any optional cast of either one with as? [String]:
let array = document.get("favoriteAritsts") as? [String]
I would like to add a document to my database collection using autoid with fields that I assign the name to in swift ui .
Get a reference of the database:
var db: Firestore!
then you can reference it with:
db.collection()
For example, if I wanted to add a person's name under a unique id:
db.collection("users").addDocument(data: [
"name": nameTextField.text // Change this to the variable you want to save
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
If you create the document without an explicit Id, our SDK will auto-generate a random one for you.
The docs are a good source of information too.
I have a simple problem. I have an existing document in cloud firestore and I simply want to add a subcollection to this document and add a document to this subcollection.
The following is my code for what I believe should do the job, but unfortunately doesn't. Also I dont get any errors.
var ref: DocumentReference? = nil
ref = db.collection("users").document("John").collection("newSubcollection").addDocument(data: [
"age": 25
]) { error in
if let err = err {
print("Error adding subcollection: \(err)")
} else {
print("subcollection added with ID: \(ref!.documentID)")
self.dismiss(animated: true, completion: nil)
}
}
The message I get is that it succesfully created the subcollection, but I dont see it. What is going wrong?