I am trying to get the document id from Firestore by executing a query like this:-
func updateStatusInFirestore() {
let orderid = saleOrder.first?.Orderid ?? ""
print(orderid)
let settings = db.settings
settings.areTimestampsInSnapshotsEnabled = true
db.settings = settings
self.db.collection("SaleOrders").whereField("orderid", isEqualTo: "\(orderid)").getDocuments { (snapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in snapshot!.documents {
self.documentid = document.documentID
print(self.documentid)
}
}
}
}
In which I am getting the order id from my model class and it is printing the value of order id but when I am trying to put it in whereField query it is not exectuing the query and I am not getting any result in my console.
If I use like this it is working
self.db.collection("SaleOrders").whereField("orderid", isEqualTo: "ji20190205091948").getDocuments
but when I use like this
let orderid = saleOrder.first?.Orderid ?? ""
self.db.collection("SaleOrders").whereField("orderid", isEqualTo: "\(orderid)").getDocuments
It is not working. What is wrong I am doing. Please help?
I Solved the problem. We just need to add one if condition to get the documentId of that particular collection from Firestore
for document in snapshot!.documents {
if document == document {
print(document.documentID)
}
}
Related
Hello there I have nested database with collection(quotes)>document(uid)>collection(quote)>document(id)
When I try to fetch the quote, I can only fetch for current user. How can I loop through uid and get everything inside quote collection for every user.
My code for fetching the quotes:
func fetchQuote() {
guard let uid = Auth.auth().currentUser?.uid else {
return
}
Firestore.firestore().collection("quotes")
.document(uid).collection("quote")
.addSnapshotListener { querySnapshot, error in
if let error = error {
print("There was an error while fetch the quotes.")
return
}
querySnapshot?.documentChanges.forEach({ change in
if change.type == .added{
let data = change.document.data()
self.quotes.append(.init(documentId:change.document.documentID, data: data))
}
})
}
}
I tried to remove the following:
.document(uid).collection("quote")
What I did is use of .collectionGroup()
Firestore.firestore().collectionGroup("quote").getDocuments(){ querySnapshot, error in
if let error = error {
print("There was an error \(error)")
return
}
querySnapshot?.documentChanges.forEach({ change in
if change.type == .added{
let data = change.document.data()
self.quotes.append(.init(documentId:change.document.documentID, data: data))
}
})
}
I've used the sample code provided by the Firebase Documentation and it prints out the error message. I have no clue if the issue is within the code or within the structure of the database, as there are also sub-collections. In this case, I am trying to retrieve the "Home Title" field, however I heard that that's not possible (I may be wrong), so I'm trying to retrieve the "Sample Wedding" document, to no avail. This is my very first time programming a project in Swift and also using Firestore.
Here's my code:
let db = Firestore.firestore()
let docRef = db.collection("Weddings").document("Sample Wedding")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
Here's my database structure:
]
You can try it like this
let db = Firestore.firestore()
db.collection("Weddings").document("Sample Wedding").getDocument {
(documentSnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
print("Document data: \(documentSnapshot)")
if let title = documentSnapshot.get("Home Title") as? String {
print(title)
}
}
}
I have been working on Firestore for retrieving data, when I tried to get data from collection->document id-> field. refer the below screen shot, I need to check companyCode matches with user entered companyCode.text
I tried with below code, need to check whether the user entered companyCodeLabel.text matches document "companyCode" and also get documentId. Can anyone suggest how to solve this?
guard let code = companyCodeLabel.text else { return }
let docRef = db.collection("Company").whereField("companyCode", isEqualTo: code).limit(to: 1)
docRef.getDocuments { (querysnapshot, error) in
if error != nil {
print("Document Error: ", error!)
} else {
if let doc = querysnapshot?.documents, !doc.isEmpty {
print("Document is present.")
}
}
}
Even tried to print the field value in collection but still have crash and same error nil
self.db.collection("Company").getDocuments { (snapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in snapshot!.documents {
let docId = document.documentID
let compCode = document.get("companyCode") as! String
let compName = document.get("companyName") as! String
print(docId, compCode, compName)
}
}
}
I tried to call in wrong db, I was trying var db = Firestore!,
The correct solutions is
Firestore.firestore().collection("Company").getDocuments { (snapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in snapshot!.documents {
let docId = document.documentID
let compCode = document.get("companyCode") as! String
let compName = document.get("companyName") as! String
print(docId, compCode, compName)
}
}
I'm currently trying to develop an ios application using Firestore, and when querying the database, I'm getting no results, as neither the if/else block execute. I'm wondering what is going wrong here...
db.collection("users").whereField("uid", isEqualTo: uid).getDocuments() { (querySnapshot, error) in
if let error = error {
print("Error getting documents: \(error.localizedDescription)")
} else {
for document in querySnapshot!.documents {
weight = document.data()["weight"]! as? Double
}
}
}
Database file structure
Update: I make a call to the database in an earlier method, and this properly returns the user's first name (when I add the weight, it also returns the correct value). But any subsequent calls fail to return anything. Hopefully that info helps.
I have the same Firestore structure like you, and this works for me:
func test() {
var accessLevel: Double?
let db = Firestore.firestore()
db.collection("users").whereField("uid", isEqualTo: UserApi.shared.CURRENT_USER_UID!).getDocuments() { (querySnapshot, error) in
if let error = error {
print("Error getting documents: \(error.localizedDescription)")
} else {
for document in querySnapshot!.documents {
accessLevel = document.data()["accessLevel"]! as? Double
print(accessLevel!)
}
}
}
}
Current uid:
// Actual logged-in User
var CURRENT_USER_UID: String? {
if let currentUserUid = Auth.auth().currentUser?.uid {
return currentUserUid
}
return nil
}
Hope it helps.
I am using Cloud Firestore as a Database for my iOS App.
I have an issue while I want to query my data when the document contains Maps (Object Type). I can not access the fields (say: firstName here) of a map (nameOnId) by having the simple query.
My code is as bellow:
let db = Firestore.firestore()
db.collection("userDetails").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
let results = document.data()
let result2 = results.compactMap({$0})
print("listedItems: \(document.documentID) => \(result2[0].value)") }}}
I read somewhere that in order to be able to access the values inside the map object, I need to flatten the map object, but having that does not give me access to them, the only thing that I could get into are a group of values inside the map so it only shows the keys and values for them like:
{
firstName = "John";
middleName = "British";
middleName = "Citizen";
gender = "M";
DOB = "8 December 2000 at 00:00:00 UTC+11";
}
the question is how to get access to a single value like "John" using the query?My data structure on Cloud Firestore
One way of doing it is as follows. Also its good practice to not force unwrap your querySnapshot (if the query does not exist, your app will crash!). Hope this helps!
let db = Firestore.firestore()
db.collection("userDetails").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else if let querySnapshot = querySnapshot {
for document in querySnapshot.documents {
let results = document.data()
if let idData = results["nameOnID"] as? [String: Any] {
let firstName = idData["firstName"] as? String ?? ""
print(firstName)
}
}
}
}