0
votes

Hi I'm new to programming and have been working on a website using Firebase Firestore as my database.

I wanted to create a subcollection in my already existing collection ('Einkaufsliste') by using the document ID. But instead it creats a new document with a different document ID and a subcollection. Using a onClick methode to create the cart. The counter is for checking if the current user ID already exists

enter image description here

enter image description here

Hier ist my JavaScript code

function clickCart() {
var docID = '';
var user = firebase.auth().currentUser;
console.log(counter)
if(counter < 1) {
    console.log('DocID: ' + docID);
    firebaseDatabase.collection('Einkaufsliste').doc().set({
        UserID: user.uid,
        UserName: user.displayName
    })
    .then(() => {
        console.log("%c Document successfully written!", 'color: green' );
        counter = counter + 1
    })
    firebaseDatabase.collection('Einkaufsliste').where('UserID', '==', user.uid).get()
    .then((snapshot) => {
        snapshot.docs.forEach(documentUserUi => {
            console.log('Function works!')
            console.log(documentUserUi.id);
            docID = documentUserUi.id;
            console.log('DocID: ' + docID);

        })
    })
    console.log("hier!")
    console.log('DocID: ' + docID);
    firebaseDatabase.collection('Einkaufsliste').doc(docID).collection('Warenkorb').doc().set({
        WarenkorbName: 'test'
    })

} else {
    console.log("%c User already exists and can't be added", "color: yellow")
    console.log(counter)

}

}

Edit I think that I found the problem docID seems to be empty, but still need to test. Also for some reason console.log('hier') output is earlier than the console.log('Funktion works!')

1

1 Answers

1
votes

The .set() accept an object as parameter and cannot be null. You would have provide a document ID as shown below:

firebaseDatabase.collection('Einkaufsliste').doc(docID).collection('Warenkorb').doc("someDocumentId").set({
        WarenkorbName: 'test'
    })

But if you are not concerned about document ID then you can use a random ID that firestore generates by using the .add() method:

firebaseDatabase.collection('Einkaufsliste').doc(docID).collection('Warenkorb').add({
        WarenkorbName: 'test'
    })