How to add subcollection to a document in Firebase Cloud Firestore

后端 未结 5 1138
一生所求
一生所求 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:03

    Here's a variation where the subcollection is storing ID values at the collection level, rather than within a document where the subcollection is a field there with additional data.

    This is useful for connecting a 1-to-Many ID mapping w/out having to drill through an additional document:

    function fireAddStudentToClassroom(studentUserId, classroomId) {
    
        var db = firebase.firestore();
        var studentsClassroomRef =
            db.collection('student_class').doc(classroomId)
              .collection('students');
    
        studentsClassroomRef
            .doc(studentUserId)
            .set({})
            .then(function () {
                console.log('Document Added ');
            })
            .catch(function (error) {
                console.error('Error adding document: ', error);
            });
    }
    

    Thanks to @Alex's answer

    This answer a bit off from the original question here, where it explicitly asks for adding a collection to a document. However, after searching for a solution for this scenario and not finding any mention in docs or on SO, this post seems like a reasonable place to share the findings

提交回复
热议问题