简体   繁体   中英

Firebase Firestore how to add subcollection

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

在此处输入图像描述

在此处输入图像描述

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!')

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'
    })

For Firebase 9 here is an example that works:

import { db } from "../firebase"; // your local firebase.js
import { addDoc collection } from "firebase/firestore";

const docRef = await addDoc(
      collection(db, "users", "sadasdsdasas", "posts"),
      {
        description: "test Description",
        title: "Test",
      }
    );


console.log("Document written with ID: ", docRef.id);

details:
"users" => parentCollection
"sadasdsdasas" => parent collection id
"posts" => subCollection to into the user with the id "sadasdsdasas"

doc: https://firebase.google.com/docs/firestore/data-model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM