Skip to content
Advertisement

Firestore: What’s the pattern for adding new data in Web v9?

I have seen in many places that to access nested documents and collections the pattern is something like db.collection("users").doc("frank").collection("pets") etc.

This makes a lot of sense to me and is easy to understand. The trouble is, my (React) project is set up in the Web version 9 way. I’ve combed the docs over and over and can’t see anything that goes beyond referencing X doc in Y collection.

I need to reference Users > uid > someCollection

But in the Web Version 9 way I can only do: doc(db, "users", uid)

How do I go deeper?

Advertisement

Answer

If you are trying to get:

JavaScript
JavaScript

The concept remains same. The path to a document has even number of segments e.g. col/doc/sub-col/sub-doc while path to a collection has odd e.g. col/doc/sub-col.

Both the methods will throw an error if invalid number of parameters are passed.


In the name-spaced version (v8), it used to look like:

JavaScript

In essence, you keep adding path segments to the same doc() or collection() methods.

JavaScript

An example with spread operator:

JavaScript

Just make sure you don’t have any leading or trailing slash if using spread operator with split().

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement