How to add subcollection to a document in Firebase Cloud Firestore

后端 未结 5 1133
一生所求
一生所求 2020-12-08 07:27

The documentation does not have any examples on how to add a subcollection to a document. I know how to add document to a collection and how to add data to a document, but h

5条回答
  •  佛祖请我去吃肉
    2020-12-08 08:06

    too late for an answer but here is what worked for me,

            mFirebaseDatabaseReference?.collection("conversations")?.add(Conversation("User1"))
                ?.addOnSuccessListener { documentReference ->
                    Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.id)
                    mFirebaseDatabaseReference?.collection("conversations")?.document(documentReference.id)?.collection("messages")?.add(Message(edtMessage?.text.toString()))
                }?.addOnFailureListener { e ->
                    Log.w(TAG, "Error adding document", e)
                }
    

    add success listener for adding document and use firebase generated ID for a path. Use this ID for the complete path for a new collection you want to add. I.E. - dbReference.collection('yourCollectionName').document(firebaseGeneratedID).collection('yourCollectionName').add(yourDocumentPOJO/Object)

提交回复
热议问题