0
0
Firebasecloud~5 mins

Getting a single document in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to get information about one specific item stored in your database. This concept shows how to fetch a single document from Firebase Firestore, so you can use or show its data.
When you want to display details of a user profile on a webpage.
When you need to check the status of a single order in an online store.
When you want to load settings for a specific device or app instance.
When you want to fetch a single blog post to show on a page.
When you need to get a single record to update or delete it.
Commands
Log in to your Firebase account to access your projects and data.
Terminal
firebase login
Expected OutputExpected
✔ Success! Logged in as user@example.com
Initialize Firestore in your project folder to set up the database rules and indexes.
Terminal
firebase init firestore
Expected OutputExpected
Firestore rules and indexes files have been created in your project directory.
Run the Node.js script that fetches a single document from Firestore and prints its data.
Terminal
node getDocument.js
Expected OutputExpected
{ name: 'Alice', age: 30, city: 'New York' }
Key Concept

If you remember nothing else from this pattern, remember: fetching a single document requires specifying its exact path in the database.

Common Mistakes
Trying to get a document without specifying the full path including collection and document ID.
Firestore needs the exact location to find the document; missing parts cause errors or empty results.
Always provide the full path like 'collectionName/documentID' when fetching a document.
Not handling the case when the document does not exist.
Your code might crash or behave unexpectedly if the document is missing.
Check if the document exists before accessing its data to avoid errors.
Summary
Use 'firebase login' to access your Firebase account.
Initialize Firestore in your project with 'firebase init firestore'.
Run a script that specifies the document path to fetch and print its data.