0

I've been working with the NodeJS implementation of Google's Firebase platform and it's an absolute dream to use. I just have a question about the different ways to fetch data from the database.

Say I have the following setup in the databse:

users (collection) -
   user_1234 (document) --
      clients (sub-collection) -
         client_abcd (document) -
          name: Lewis
          email: [email protected]
          etc...

and I want to fetch data from the client_abcd document stored in the users sub-collection of clients, I have a few ways of referencing it in the call:

Either by referencing the document through a chain of collections:
db.collection('users').doc('user_1234').collection('clients').doc('client_abcd').get().then(user => {return user});

Or, I can reference the document directly using a template literal:
db.doc('users/user_1234/clients/client_abcd').get().then(user => {return user});

No other than the clear difference in cleaner code (in my opinion), i'm not about the benefits of each. For example, does the first solution require more calls to the database and thus more usage on the available quota for that period?

Another difference that is clear between the two is that in the first you can get multiple documents from a collection whereas the latter is just calling the database for a single document, so that's an advantage the first has.

In the official documentation, only the first option is shown to be used: https://firebase.google.com/docs/firestore/query-data/get-data

If anyone has worked with this library before and has a better insight on this it would be really useful.

Thank you in advance!

1 Answer 1

2

There is no difference between these two calls in how they access the backend (and thus how they get billed):

db.collection('users').doc('user_1234').collection('clients').doc('client_abcd')
db.doc('users/user_1234/clients/client_abcd')

The difference is purely syntactic, so you can use whichever one you prefer.


You can also pass a path to the collection method, so for example to get all documents in a subcollection, you could do either of these:

db.collection('users').doc('user_1234').collection('clients')
db.collection('users/user_1234/clients')
Sign up to request clarification or add additional context in comments.

1 Comment

That's great information thank you very much! I did not know you could also achieve the same with passing a path to a collection so that's useful. Thank you!

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.