user43286
user43286

Reputation: 2321

How to make firestore create nested object as sub collections on write?

Consider my below code. I want this code to create a sub-collection called items under the collection test, but right the items added an array field in test collection. Note, this is for firestore not firebase realtime db.

data = {
"first": "new",
"born": 1815,
"items": [
  {
    "field": 2
  }
 ]
};
db.collection("test").add(data)

Upvotes: 5

Views: 10060

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

Your data object is a single object, and when you store a single object as a document using the code you gave, that object will occupy that single document.

If you want to write data to a subcollection, you'll have to write it separately, being very clear to the API that you want a subcollection underneath it:

db.collection("test")
    .document("doc_id")
    .collection("items")

or:

db.collection("test/doc_id/items")

To put it another way, if you want to write any two documents, you'll have to perform to two add/update/create calls at different locations. You can't create two documents with one call.

Upvotes: 13

Related Questions