Reputation: 1888
I want to create a nested collection as I want to store more fields than a map of a document can contain. My document names are defined so that I can fetch data on a name-based path. So I do not want to create a dynamic name. With limited names and potentially many fields under these, I think a collection is a better option.
The nested collection will not create without data set parent document. setting data seems unnecessary to me. But I thought to set the creation date. And add collections on that document. But seems I can not create all that in one defined path. Code will explain more:
val db = Firebase.firestore
val where = "Denvar"
val what = "WalkingOrRunning"
val docData = hashMapOf(
"date" to Timestamp(Date()),
"duration" to "10 min"
"comment" to "Dummy comment"
)
//document who got fields like name, UsersActivity got doc Start date previously set.
val userPath = db.collection("Users").document(who)
.collection("UsersActivity").document("history").set(docData) // want to continue next line here but that will create empty document thus collection will not save so adding dummy fields
userPath.collection(what).document(where).set(docData) // this does not create collection either
So what is your suggestion for my data structure?
Upvotes: 1
Views: 985
Reputation: 138834
But seems I can not create all that in one defined path.
You cannot do that in a single go. You need to create two different operations. This is because, in the following line of code:
val userPath = db.collection("Users").document(who)
.collection("UsersActivity").document("history").set(docData)
The type of the "userPath" object is Task<Void>
because this is the type of the object that is returned by the DocumentReference#set(Object data) method. So there is no way you can continue chaining other .collection()
or .document()
method calls after it because the Task class doesn't contain such methods. In order to achieve what you want, you need to create two separate operations and reuse the "userPath" object like below:
val userPath = db.collection("Users").document(who)
.collection("UsersActivity").document("history")
Now the "userPath" object is of type DocumentReference and right after that you can call set() and add the object to the database:
userPath.set(docData).addOnCompleteListener(/* ... /*)
Now to add new documents within a sub-collection of the history
document, the following line of code will perfectly fine:
userPath.collection(what).document(where).set(docData).addOnCompleteListener(/* ... /*)
Upvotes: 2