ホーム > GCP > How to Save Data to Cloud Firestore with Cloud Functions
GCP

How to Save Data to Cloud Firestore with Cloud Functions

Thank you for your continued support.
This article contains advertisements that help fund our operations.

This post summarizes how to save data to Firebase's Firestore using Google Cloud Platform's Cloud Functions.

Introduction

In my previous article, I wrote about my first experience with Cloud Functions.

Introduction to GCP Cloud Functions and How to Run Node.js Code

This time, I will discuss how to save data to Firebase using Cloud Functions.

To begin, move to the functions directory and run the following command:

cd ~~~
npm i firebase-admin --save

Check the package.json file to confirm that the module was successfully installed.

Creating a Firestore Database

Go to the Firebase console, select database from the left menu, and create a new database. Then, click on the gear icon at the top left, generate a secret key, download the JSON file, and place it in a path directory under the functions directory. Remember to name the file key.json.

Saving Data to Firestore

Edit the index.js file to include the following code snippet:

const functions = require("firebase-functions")
const admin = require("firebase-admin")

var serviceAccount = require("./path/key.json")

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://testapp-80832.firebaseio.com",
})

var db = admin.firestore()
var postsRef = db.collection("posts")

exports.helloWorld = functions.https.onRequest((request, response) => {
  postsRef.add({
    name: "TestTestTest",
  })

  const getItems = async () => postsRef.get()

  async function item() {
    let answer = []
    const items = await getItems()
    items.forEach(snap => {
      answer.push(snap.data().name)
    })
    response.send(answer)
  }
  item()
})

Run firebase serve --only functions in the terminal to start the functions. Ensure that the Cloud Firestore API is enabled in your GCP project.

Explanation

The code snippet above shows how to save data to Firestore and retrieve it. You can also refer to the Firebase documentation for more information on data retrieval methods.

Conclusion

In this article, we covered the steps to save and retrieve data from Firestore using Cloud Functions. Feel free to reach out on Twitter if you have any questions or need clarification on any part of the process.

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!