Add a document to a non-existent subcollection in Firestore

Viewed 1125

Hope this isn't too obvious but I am really stumped at this point. I am having trouble adding a document to a subcollection that does not exist in Firebase Firestore.

The code works perfectly when adding to a subcollection that already exists.

db.collection("collectionId").doc(docId).collection("subcollectionId").doc(subdocId).collection("items").add({
    userName,
    isActive: true        
}).then(function() {
    console.log("Document successfully written!");
}).catch(function(error) {
    console.error("Error writing document: ", error);
});

To be clear here, the sub-sub-collection "items" exists in some of my sub-collections and has not yet been created in others. When I attempt to add a document to "items" using the above code in a subcollection that already has other "items", it works with the following result:

Document successfully written!

When I attempt to add a document to "items" in a subcollection where "items" does not exist, it does not add the item and there is nothing written to the console.

Thanks for the help in advance!

UPDATE WITH SCREENSHOTS AS ASKED FOR:

Success: enter image description here

Failure: enter image description here

1 Answers

When you write a document to any collection or subcollection that doesn't exist, it will then immediately exist. This behavior never changes. The SDK will never give you an indicator of success without actually writing the document.

If you're saying that the document just doesn't get written, then it sounds like you're not looking in the right place. Refreshing the Firebase or Cloud console in your web browser helps to reveal newly created collections. It will also help if you know exactly what the value of subdocId is here, so you know for sure where to look.

Related