0

How would I go about adding a new document in Firebase/Cloud Firestore with a nested collection?

const createDocument = () => {
        const documentName = prompt('Enter document name:');
        if (documentName) {
            db.collection('despacito').add({
                name: documentName,
            })
}

Any suggestions? Thank you for your time.

1 Answer 1

2

Per the data model doc, Collections and documents are created implicitly in Cloud Firestore. Simply assign data to a document within a collection. If either the collection or document does not exist, Cloud Firestore creates it.

So no need to actually create a document with a nested collection.

Per the subcollections documentation to reference a new document in a subcollection you can reference it as:

const messageRef = db.collection('rooms').doc('roomA').collection('messages').doc('message1');

As you are using the .add method, it should be something like:

db.collection('despacito').doc('documentName').collection('subcollectionname').add({
                name: nesteddocumentName,
            })
Sign up to request clarification or add additional context in comments.

2 Comments

Very helpful. Thank you.
no problem, feel free to upvote/accept the answer for reference for future users with same issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.