0Pricing
Indie Hacker Mobile Apps · 课时

云数据库与函数

使用实时数据库(例如 Firestore),并部署无服务器云函数来实现自定义后端逻辑。

云数据库与函数 是 CoddyKit 上的免费 Indie Hacker Mobile Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Indie Hacker Mobile Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Indie Hacker Mobile Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Cloud Databases Unveiled

Welcome! Today, we'll explore cloud databases and serverless functions, essential tools for scalable mobile apps. They provide robust, managed backends without the hassle of server maintenance.

We'll focus on Firestore, a popular choice for real-time data, and Cloud Functions for custom backend logic.

Firestore's Data Model

Cloud Firestore is a flexible, scalable NoSQL document database. Unlike traditional relational databases with tables and rows, Firestore organizes data into collections and documents.

Each document contains key-value pairs, known as fields. Documents live within collections, and collections can even contain subcollections.

Structuring Your App Data

Understanding collections and documents is key to structuring your app's data efficiently. Imagine a simple e-commerce app:

  • users (collection)
    • user_alice_id (document)
      • name: "Alice"
      • email: "alice@example.com"
  • products (collection)
    • product_xyz_id (document)
      • name: "Cool Gadget"
      • price: 99.99

Adding Data with Ease

Adding data to Firestore is straightforward. You can use add() to let Firestore generate a unique document ID, or set() to specify your own ID or overwrite an existing document.

Here's how to add a new user to a 'users' collection:

db.collection("users").add({
  name: "Bob",
  email: "bob@example.com",
  status: "active"
})
.then((docRef) => {
  console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
  console.error("Error adding document: ", error);
});

Fetching Data on Demand

To retrieve a document or a collection of documents once, you use the get() method. This is useful for data that doesn't require constant, real-time updates.

Let's fetch a specific user's data using their document ID:

db.collection("users").doc("bob_doc_id").get()
  .then((doc) => {
    if (doc.exists) {
      console.log("Document data:", doc.data());
    } else {
      console.log("No such document!");
    }
  })
  .catch((error) => {
    console.error("Error getting document:", error);
  });

Keeping Data Live with Snapshots

Firestore's real-time capabilities are powerful. By using onSnapshot(), you can listen for changes to documents or collections. Whenever data changes on the backend, your app receives instant updates.

This snippet demonstrates listening to a single document for real-time changes:

db.collection("products").doc("prod_xyz").onSnapshot((doc) => {
  if (doc.exists) {
    console.log("Current product data:", doc.data());
  } else {
    console.log("Product removed or never existed!");
  }
});
// This listener keeps your app updated automatically

Serverless Logic with Functions

Cloud Functions are serverless pieces of code that run in response to specific events. They let you execute custom backend logic without needing to manage or provision any servers.

They're perfect for extending your BaaS (like Firebase) with custom features, security rules, or integrations.

What Makes a Function Run?

Cloud Functions are 'event-driven,' meaning they only run when a specific event occurs. These events are called triggers. Common types include:

  • HTTP triggers: For creating API endpoints.
  • Firestore triggers: React to document creation, updates, or deletions.
  • Authentication triggers: Respond to user sign-ups or deletions.
  • Scheduled triggers: Run functions at specific times (e.g., daily cleanup).

Your First HTTP Cloud Function

Let's create a simple Cloud Function that responds to an HTTP request. This is like building a tiny, serverless API endpoint. It's a great way to handle custom logic that your mobile app might need.

This example will return a basic "Hello from Firebase!" message.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.helloHttp = functions.https.onRequest((request, response) => {
  // Set CORS headers for web access, if needed
  response.set('Access-Control-Allow-Origin', '*'); 
  response.set('Access-Control-Allow-Methods', 'GET, POST');
  response.status(200).send("Hello from Firebase!");
});

Automating with Functions + DB

Cloud Functions and Firestore are a powerful combination. Functions can automatically react to changes in your Firestore database, allowing you to:

  • Update aggregate counts (e.g., total likes on a post).
  • Perform data validation or sanitization.
  • Send notifications or emails after a user action.

This keeps your app's logic robust and efficient, handling backend tasks seamlessly.

Cloud Logic Check

Test your understanding of cloud databases and serverless functions.

Databases & Functions Summary

You've explored the core concepts of Cloud Firestore for scalable, real-time data storage using a flexible NoSQL document model. You also learned about Cloud Functions, which enable you to deploy serverless backend logic in response to various triggers.

Mastering these tools is fundamental for building dynamic, robust, and efficient indie mobile apps!

常见问题解答

「云数据库与函数」课时是免费的吗?

是的 — 「云数据库与函数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Indie Hacker Mobile Apps 课程的其余内容,请升级到 CoddyKit PRO。 Indie Hacker Mobile Apps 课程共包含 4 节课。

「云数据库与函数」这节课中我会学到什么?

使用实时数据库(例如 Firestore),并部署无服务器云函数来实现自定义后端逻辑。 你通过在浏览器中直接运行的动手代码来练习 Indie Hacker Mobile Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Indie Hacker Mobile Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Indie Hacker Mobile Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「云数据库与函数」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Indie Hacker Mobile Apps 课中编写并运行代码吗?

能。每节 Indie Hacker Mobile Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. BaaS 平台入门
  2. 用户身份验证与安全
  3. 云数据库与函数
  4. 使用 BaaS 实现实时数据与推送通知
← 返回 Indie Hacker Mobile Apps