0
votes

In cloud firestore, I want to add the value form to collection A and then all the same value to another collection B, but collection B is inside collection A. Currently I want to get the id of the document while adding the data to collection A and then use this.firestore.collection(A).doc(id).collection(B).add(data), but currently I cannot get the ID of the document This one is my code to get ID when adding data to collection A.

onSubmit(form: NgForm) {
        let data = form.value;
        lastID = '';
        this.firestore
            .collection('Users')
            .add(data)
            .then(function (docRef) {
                this.lastID = docRef.id;
            });
        this.firestore.collection('Users').doc(lastID).collection('profile').add(data);
        this.resetForm(form);
    }
1

1 Answers

1
votes

You can do the second add inside the callback of the first. Also note that you should use an arrow function in your callback to preserve the value of this from the outer scope:

        this.firestore
            .collection('Users')
            .add(data)
            .then(docRef => {
                this.lastID = docRef.id;
                return this.firestore.collection('Users').doc(this.lastID).collection('profile').add(data);
            })
            .then(() => {
                this.resetForm(form);
            });