arrow_back

Firebase Essentials: Firestore Database Write with JavaScript

登录 加入
访问 700 多个实验和课程

Firebase Essentials: Firestore Database Write with JavaScript

实验 30 分钟 universal_currency_alt 1 积分 show_chart 入门级
info 此实验可能会提供 AI 工具来支持您学习。
访问 700 多个实验和课程

gem-firebase-firestore-write-javascript

Google Cloud self-paced labs logo

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:

Your Cloud Platform project in this session is set to YOUR_PROJECT_ID

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

  2. Your output should now look like this:

Output:

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@qwiklabs.net To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = <project_ID>

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Overview

This lab guides you through creating a Firebase Firestore database and writing data to it using a JavaScript application. You'll learn how to initialize Firebase, structure your data, and use the Firebase CLI for authentication. This eliminates the need for a custom service account.

Task 1. Adding a Firebase Project to Google Cloud

Attach a new Firebase project to your Google Cloud proiect by visting the Firebase console.

  1. Go to the Firebase Console.

    https://console.firebase.google.com/ Note:
    Navigate to the Firebase Console in your browser.
  2. Click Create a Firebase Project and follow the instructions to create a new project.

    Note:
    On the **Create a project** page, scroll down to the bottom of the screen and click **Add Firebase to Google Cloud Project**.
  3. On the following screen, enter the Google Cloud project identifier shown below.

    {{{ project_0.project_id | "PROJECT_ID" }}} Note:
    This project identifier is linked to a Google Cloud project. Accept the Firebase terms and conditions to create the Firebase project.
  4. Follow the remaining instructions to create a new Firebase project.

    Note:
    Firebase includes options for billing and analytics. These options are not used in this lab, so accept the default options to complete the creation of the Firebase project.

Task 2. Set Up Your Environment

Return to Google Cloud and use CloudShell to configure your Google Cloud project and initialize Firebase.

  1. Set your project ID.

    gcloud config set project {{{ project_0.project_id | "PROJECT_ID" }}} Note:
    This command sets your active project.
  2. Set your default region.

    gcloud config set run/region {{{ project_0.default_region | "REGION" }}} Note:
    This command sets your active region.
  3. Set your default zone.

    gcloud config set compute/zone {{{ project_0.default_zone | "ZONE" }}} Note:
    This command sets your active zone.
  4. Enable the necessary APIs.

    gcloud services enable compute.googleapis.com container.googleapis.com iap.googleapis.com firebase.googleapis.com firebaseextensions.googleapis.com eventarc.googleapis.com pubsub.googleapis.com storage.googleapis.com run.googleapis.com Note:
    This command enables the Google APIs required for this lab.
  5. Create a Firestore database in Native mode.

    gcloud firestore databases create --location=nam5 --database='(default)' Note:
    This command provisions a Firestore database in the `nam5` (North America) multi-region. The database must exist before you can deploy or run code that interacts with it. You can choose a different region if needed.

Task 3. Configure the Firebase Environment

Enable the Firebase environment to use for development.

  1. Install the Firebase CLI.

    npm install -g firebase-tools Note:
    This command installs the Firebase CLI globally.
  2. Create a new directory for the project.

    mkdir firestore-app && cd firestore-app Note:
    This command creates a folder for the lab content. This folder will contain the code and configurations generated during the lab.
  3. Log in to Firebase using the CLI:

    firebase login --no-localhost Note:
    This command authenticates the Firebase CLI with your Google account.
  4. Initialize Firebase in your project directory.

    firebase init Note:
    This command initializes a Firebase project in the current directory.
    When prompted:
    • Select Firestore and Functions.
    • For Firestore, accept the default location.
    • For Functions, choose JavaScript and decline ESLint.

Task 4. Write Data to Firestore

Now, write some data to your Firestore database using JavaScript. For convienience a Firebase Cloud Function will be used to populate the Firestore database.

  1. Replace functions/index.js file with the following code:

    // functions/index.js const {initializeApp} = require("firebase-admin/app"); const {getFirestore} = require("firebase-admin/firestore"); // Import onRequest instead of onCall const {onRequest} = require("firebase-functions/v2/https"); const {setGlobalOptions} = require("firebase-functions/v2"); initializeApp(); setGlobalOptions({ region: '{{{ project_0.default_region | "REGION" }}}' }); // Use onRequest for a standard HTTP endpoint exports.addMessage = onRequest(async (req, res) => { // Check that the request method is POST if (req.method !== 'POST') { res.status(405).send({ error: 'Method Not Allowed! Please use POST.' }); return; } // Get the text from the request body directly. // The {"data": ...} wrapper is not needed for onRequest functions. const text = req.body.text; // Validate the input and send back a standard HTTP error response if (!text || text.length > 200) { res.status(400).send({ error: 'The message text is either missing or too long (max 200 characters).', }); return; } try { const writeResult = await getFirestore() .collection('messages') .add({ original: text }); console.log(`Message with ID: ${writeResult.id} added.`); // Send a success response res.status(200).send({ message: `Message with ID: ${writeResult.id} added to Firestore.` }); } catch (error) { console.error("Error writing to Firestore:", error); res.status(500).send({ error: 'An internal error occurred.' }); } }); Note:
    This code defines a Firebase Function that writes a message to the `messages` collection in Firestore. It uses the Firebase Admin SDK, which leverages the Firebase CLI's authentication for simplified access.
  2. Replace the functions/package.json file with the following configuration to set the correct JavaScript engine and add the required dependencies.

    { "name": "functions", "scripts": { "lint": "eslint .", "serve": "firebase emulators:start --only functions", "shell": "firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions", "logs": "firebase functions:log" }, "engines": { "node": "22" }, "main": "index.js", "dependencies": { "firebase-admin": "^11.8.0", "firebase-functions": "^4.6.0" }, "devDependencies": { "@firebase/rules-unit-testing": "^2.0.2", "eslint": "^8.15.0", "eslint-config-google": "^0.14.0", "firebase-functions-test": "^3.0.0" }, "private": true } Note:
    Ensure the `engines/node` field is set to `v22`, the `firebase-admin` dependency is included, and `firebase-functions` is `v4.6.0` or later.
  3. Install the dependencies.

    cd functions && npm install Note:
    This command installs all the necessary packages defined in your `package.json` file.
  4. Return to the Firebase application folder.

    cd ~/firestore-app Note:
    This command returns to the parent folder, ready for deployment.
  5. Deploy the function to Firebase.

    firebase deploy --only functions Note:
    This command deploys your Firebase Function to the cloud.

    If you see an error relating to "There was an issue deploying your functions. Verify that your project has a Google App Engine instance setup at https://console.cloud.google.com/appengine and try again." This indicates a background processes have not completed.

    Please wait a couple of minutes before trying the deploy command again.

Task 5. Test the Function

Verify that your Firebase Cloud Function is writing data to Firestore correctly.

  1. List the available Firebase Cloud Functions.

    firebase functions:list Note:
    This command lists the available Firebase Functions for the active project.

    EXPECTED OUTPUT

    ┌────────────┬─────────┬─────────┬─────────────┬────────┬──────────┐ │ Function │ Version │ Trigger │ Location │ Memory │ Runtime │ ├────────────┼─────────┼─────────┼─────────────┼────────┼──────────┤ │ addMessage │ v2 │ https │ {{{ project_0.default_region | REGION }}} │ 256 │ nodejs22 │ └────────────┴─────────┴─────────┴─────────────┴────────┴──────────┘
  2. Get the URI for the Firebase Cloud Function.

    FUNCTION_URI=$(gcloud functions describe addMessage --region {{{ project_0.default_region | "REGION" }}} --format=json | jq -r .serviceConfig.uri) Note:
    This command retrieves the `addMessage` function object and extracts the URI.
  3. Call the Firebase Cloud Function using curl.

    MESSAGE_TEXT="Hello from the CLI!" curl -X POST "$FUNCTION_URI" -H "Content-Type: application/json" -d '{"text":"'"$MESSAGE_TEXT"'"}' Note:
    This command invokes the `addMessage` function with the provided data. The function name is case-sensitive.
    {"message":"Message with ID: 9GMxSOZp0yynY0I57Dav added to Firestore."}
  4. Check the Firestore console to confirm the data has been written.

    Open the Firebase console for your project. Navigate to Firestore Database, and you should see a new document in the 'messages' collection. Note:
    Verify that the data has been written to Firestore.

Congratulations!

Congratulations! You've successfully created a Firestore database and written data to it using a JavaScript function. You also learned how to use the Firebase CLI for authentication, simplifying the development process. You can now expand on this foundation to build more complex applications that leverage Firestore's capabilities.

Additional Resources

Manual Last Updated Aug 14, 2025

Lab Last Tested Aug 14, 2025

准备工作

  1. 实验会创建一个 Google Cloud 项目和一些资源,供您使用限定的一段时间
  2. 实验有时间限制,并且没有暂停功能。如果您中途结束实验,则必须重新开始。
  3. 在屏幕左上角,点击开始实验即可开始

使用无痕浏览模式

  1. 复制系统为实验提供的用户名密码
  2. 在无痕浏览模式下,点击打开控制台

登录控制台

  1. 使用您的实验凭证登录。使用其他凭证可能会导致错误或产生费用。
  2. 接受条款,并跳过恢复资源页面
  3. 除非您已完成此实验或想要重新开始,否则请勿点击结束实验,因为点击后系统会清除您的工作并移除该项目

此内容目前不可用

一旦可用,我们会通过电子邮件告知您

太好了!

一旦可用,我们会通过电子邮件告知您

一次一个实验

确认结束所有现有实验并开始此实验

使用无痕浏览模式运行实验

请使用无痕模式或无痕式浏览器窗口运行此实验。这可以避免您的个人账号与学生账号之间发生冲突,这种冲突可能导致您的个人账号产生额外费用。