I need to add user record using collection path. I'm using following code:
var todays_date : String = ""
let dateFormatter : DateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMddyyyy"
let date = Date()
todays_date = dateFormatter.string(from: date)
docRef = Firestore.firestore().document("userData/scriptureTracking/users/" + user_id.replacingOccurrences(of: " ", with: "_") + "/" + todays_date)
docRef.setData(dataToSave) { (error) in
if let error = error {
print("CloudFirestore Got error: \(error.localizedDescription)")
} else {
print("CloudFirestore: Data has been saved!")
}
}
Somehow it is not able to reference it properly. It is crashing out at this line. If I remove last backslash and 'todays_date' then it is working fine (Saving data using docRef). But I need both 'user_id' and 'todays_date' for querying later. Any idea?
This is because your docRef isn't pointing to a document.
Remember, all paths in Cloud Firestore follow the pattern of collection / document / collection / document / etc.
So if you remove the last part of your function and just have:
docRef = Firestore.firestore().document("userData/scriptureTracking/users/" + user_id.replacingOccurrences(of: " ", with: "_"))
What you end up with is a collection called userData, with a document called scriptureTracking, which has a collection called users, which has a document that's equal to the user ID.
If you add on the date to the end of that, then you have a collection that's equal to 06292018 (or whatever). Most likely, you want to make that a document inside a subcollection as well. So you probably want something like...
docRef = Firestore.firestore().document("userData/scriptureTracking/users/" + user_id.replacingOccurrences(of: " ", with: "_") + "/dailyEntries/" + todays_date)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With