Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a collection in firebase if it does not exist and add a document to it? [duplicate]

I have a collection "Houses" in firebase which is supposed to contain documents. So my function takes the document data and adds it to the given collection name.

If the collection "Houses" does not exist, how do I create a new one programmatically and add data to it? (Some way to check if the collection already exists, and make a new one if it returns false?)

This is my addData function:

exports.addData = functions.https.onCall((data, context) => {

    let validated = true;

    validateForm(data);

    if (validated === false) {
        console.log('Data cannot be validated. Misses the correct attributes')
    } else {
        addAttributes(data);
        for (let i=0; i<data.length; i++) {
                db.collection('Houses')
                .add(data[i])
                .then((docRef) => {
                    console.log('Success ', docRef.id); 
                    return { message: "Done" }
                })
                .catch(err => {
                    console.log('Error logged', err);
                })
        }
    }
})

1 Answers

Firestore collections are logical entities for organizing your data, not something that explicitly needs to be created. If you add data to a collection it is implicitly created -- you don't have to do anything!

// "Houses" collection doesn't exist
await db.collection('Houses').add(data);
// now it does!
like image 119
Michael Bleigh Avatar answered Nov 17 '25 15:11

Michael Bleigh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!