Bắt đầu sử dụng Cloud Firestore phiên bản dành cho doanh nghiệp

Hướng dẫn nhanh này cho bạn biết cách thiết lập Cloud Firestore phiên bản dành cho doanh nghiệp, thêm dữ liệu, sau đó sử dụng các thao tác Core hoặc Pipeline để truy vấn dữ liệu mà bạn vừa thêm trong bảng điều khiển Firebase.

Cloud Firestore hỗ trợ SDK dành cho thiết bị di động hoặc web và thư viện ứng dụng máy chủ:

  • Cloud Firestore hỗ trợ SDK cho Android, iOS, web và nhiều nền tảng khác. Kết hợp với Cloud Firestore Security RulesFirebase Authentication, các SDK dành cho thiết bị di động và web hỗ trợ cấu trúc ứng dụng không cần máy chủ, trong đó các ứng dụng kết nối trực tiếp với cơ sở dữ liệu Cloud Firestore của bạn.

  • Cloud Firestore hỗ trợ thư viện ứng dụng máy chủ cho Java, Node.js và Python. Sử dụng các thư viện ứng dụng này để thiết lập môi trường máy chủ đặc quyền có quyền truy cập đầy đủ vào cơ sở dữ liệu của bạn. Tìm hiểu thêm về các thư viện này trong bài viết Hướng dẫn nhanh về thư viện ứng dụng máy chủ.

Tạo cơ sở dữ liệu Cloud Firestore phiên bản dành cho doanh nghiệp

  1. Nếu chưa có, bạn cần tạo một dự án Firebase: Trong bảng điều khiển Firebase, hãy nhấp vào Thêm dự án, sau đó làm theo hướng dẫn trên màn hình để tạo một dự án Firebase hoặc thêm các dịch vụ Firebase vào một dự án Google Cloud hiện có.

  2. Mở dự án của bạn trong bảng điều khiển Firebase. Trong bảng điều khiển bên trái, hãy mở rộng mục Build (Tạo) rồi chọn Cơ sở dữ liệu Firestore.

  3. Nhấp vào Tạo cơ sở dữ liệu.

  4. Chọn Doanh nghiệp cho chế độ cơ sở dữ liệu.

  5. Chọn Firestore ở chế độ gốc cho chế độ hoạt động, hỗ trợ các hoạt động Core và Pipeline.

  6. Chọn một vị trí cho cơ sở dữ liệu của bạn.

  7. Chọn chế độ khởi động cho Cloud Firestore Security Rules:

    Chế độ kiểm thử

    Phù hợp để bắt đầu sử dụng các thư viện ứng dụng di động và web, nhưng cho phép mọi người đọc và ghi đè dữ liệu của bạn. Sau khi kiểm thử, hãy nhớ xem xét phần Bảo mật dữ liệu của bạn.

    Để bắt đầu với web, nền tảng Apple hoặc SDK Android, hãy chọn chế độ kiểm thử.

    Chế độ sản xuất

    Từ chối mọi lượt đọc và ghi từ ứng dụng di động và ứng dụng web. Các máy chủ ứng dụng được xác thực (Python) vẫn có thể truy cập vào cơ sở dữ liệu của bạn.

    Nhóm Cloud Firestore Security Rules ban đầu sẽ áp dụng cho cơ sở dữ liệu Cloud Firestore mặc định của bạn. Nếu tạo nhiều cơ sở dữ liệu cho dự án, bạn có thể triển khai Cloud Firestore Security Rules cho từng cơ sở dữ liệu.

  8. Nhấp vào Tạo.

Khi bạn bật Cloud Firestore phiên bản dành cho doanh nghiệp, API này cũng sẽ được bật trong Cloud API Manager.

Thiết lập môi trường phát triển

Thêm các phần phụ thuộc và thư viện ứng dụng cần thiết vào ứng dụng của bạn.

Web

  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng web.
  2. SDK Cloud Firestore có sẵn dưới dạng một gói npm.
    npm install firebase@12.9.0 --save
    Bạn cần nhập cả Firebase và Cloud Firestore.
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
iOS+

Làm theo hướng dẫn để thêm Firebase vào ứng dụng Apple.

Sử dụng Swift Package Manager để cài đặt và quản lý các phần phụ thuộc của Firebase.

  1. Trong Xcode, khi dự án ứng dụng của bạn đang mở, hãy chuyển đến File (Tệp) > Swift Packages (Gói Swift) > Add Package Dependency (Thêm phần phụ thuộc của gói).
  2. Khi được nhắc, hãy thêm kho lưu trữ SDK của Firebase cho các nền tảng Apple:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. Chọn thư viện Firestore.
  5. Khi hoàn tất, Xcode sẽ tự động bắt đầu phân giải và tải các phần phụ thuộc xuống ở chế độ nền.
Android
  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng Android.
  2. Bằng cách sử dụng BoM trên Android cho Firebase, hãy khai báo phần phụ thuộc cho thư viện Cloud Firestore cho Android trong tệp Gradle (ở cấp ứng dụng) trong mô-đun của bạn (thường là app/build.gradle.kts hoặc app/build.gradle).
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:34.8.0"))
    
        // Declare the dependency for the Cloud Firestore library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore")
    }

    Bằng cách sử dụng BoM trên Android cho Firebase, ứng dụng của bạn sẽ luôn sử dụng những phiên bản tương thích của thư viện Android trên Firebase.

    (Cách khác) Khai báo phần phụ thuộc của thư viện Firebase mà không sử dụng BoM

    Nếu chọn không sử dụng Firebase BoM, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phần phụ thuộc của thư viện đó.

    Xin lưu ý rằng nếu sử dụng nhiều thư viện Firebase trong ứng dụng, bạn nên sử dụng BoM để quản lý các phiên bản thư viện, nhằm đảm bảo rằng tất cả các phiên bản đều tương thích.

    dependencies {
        // Declare the dependency for the Cloud Firestore library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore:26.1.0")
    }

    Bạn đang tìm kiếm một mô-đun thư viện dành riêng cho Kotlin? Bắt đầu từ bản phát hành tháng 10 năm 2023, cả nhà phát triển Kotlin và Java đều có thể phụ thuộc vào mô-đun thư viện chính (để biết thông tin chi tiết, hãy xem Câu hỏi thường gặp về sáng kiến này).

Khởi chạy Cloud Firestore

Khởi động một phiên bản của Cloud Firestore:

Web

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
    FIREBASE_CONFIGURATION
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// When initializing Firestore, remember to use the name of the database you created earlier:
const db = initializeFirestore(app, {}, 'your-new-enterprise-database');

Thay thế FIREBASE_CONFIGURATION bằng firebaseConfig của ứng dụng web.

Để duy trì dữ liệu khi thiết bị mất kết nối, hãy xem tài liệu Bật dữ liệu ngoại tuyến.

Swift
import FirebaseCore
import FirebaseFirestore

FirebaseApp.configure()

// When initializing Firestore, remember to use the name of the database you created earlier:
let db = Firestore.firestore(database: "your-new-enterprise-database")

Kotlin

// Access a Cloud Firestore instance from your Activity
// When initializing Firestore, remember to use the name of the database you created earlier:
val firestore = FirebaseFirestore.getInstance("your-new-enterprise-database")

Java

// Access a Cloud Firestore instance from your Activity
// When initializing Firestore, remember to use the name of the database you created earlier:
FirebaseFirestore firestore = FirebaseFirestore.getInstance("your-new-enterprise-database");

Thêm dữ liệu bằng cách sử dụng các thao tác chính

Để khám phá các thao tác Core và thao tác Pipeline để truy vấn dữ liệu, hãy thêm dữ liệu vào cơ sở dữ liệu bằng cách sử dụng các thao tác Core.

Cloud Firestore lưu trữ dữ liệu trong Tài liệu, được lưu trữ trong Bộ sưu tập. Cloud Firestore sẽ tạo các bộ sưu tập và tài liệu một cách ngầm ẩn vào lần đầu tiên bạn thêm dữ liệu vào tài liệu. Bạn không cần phải tạo rõ ràng các bộ sưu tập hoặc tài liệu.

Tạo một bộ sưu tập và tài liệu mới bằng mã ví dụ sau.

Web

import { collection, addDoc } from "firebase/firestore"; 

try {
  const docRef = await addDoc(collection(db, "users"), {
    first: "Ada",
    last: "Lovelace",
    born: 1815
  });
  console.log("Document written with ID: ", docRef.id);
} catch (e) {
  console.error("Error adding document: ", e);
}

Web

db.collection("users").add({
    first: "Ada",
    last: "Lovelace",
    born: 1815
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});
Swift
Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
// Add a new document with a generated ID
do {
  let ref = try await db.collection("users").addDocument(data: [
    "first": "Ada",
    "last": "Lovelace",
    "born": 1815
  ])
  print("Document added with ID: \(ref.documentID)")
} catch {
  print("Error adding document: \(error)")
}

Kotlin

// Create a new user with a first and last name
val user = hashMapOf(
    "first" to "Ada",
    "last" to "Lovelace",
    "born" to 1815,
)

// Add a new document with a generated ID
db.collection("users")
    .add(user)
    .addOnSuccessListener { documentReference ->
        Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "Error adding document", e)
    }

Java

// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("first", "Ada");
user.put("last", "Lovelace");
user.put("born", 1815);

// Add a new document with a generated ID
db.collection("users")
        .add(user)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
            }
        });

Bây giờ, hãy thêm một tài liệu khác vào bộ sưu tập users. Xin lưu ý rằng tài liệu này có một cặp khoá-giá trị (tên đệm) không xuất hiện trong tài liệu đầu tiên. Các tài liệu trong một bộ sưu tập có thể chứa nhiều bộ thông tin.

Web

// Add a second document with a generated ID.
import { addDoc, collection } from "firebase/firestore"; 

try {
  const docRef = await addDoc(collection(db, "users"), {
    first: "Alan",
    middle: "Mathison",
    last: "Turing",
    born: 1912
  });

  console.log("Document written with ID: ", docRef.id);
} catch (e) {
  console.error("Error adding document: ", e);
}

Web

// Add a second document with a generated ID.
db.collection("users").add({
    first: "Alan",
    middle: "Mathison",
    last: "Turing",
    born: 1912
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});
Swift
Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
// Add a second document with a generated ID.
do {
  let ref = try await db.collection("users").addDocument(data: [
    "first": "Alan",
    "middle": "Mathison",
    "last": "Turing",
    "born": 1912
  ])
  print("Document added with ID: \(ref.documentID)")
} catch {
  print("Error adding document: \(error)")
}

Kotlin

// Create a new user with a first, middle, and last name
val user = hashMapOf(
    "first" to "Alan",
    "middle" to "Mathison",
    "last" to "Turing",
    "born" to 1912,
)

// Add a new document with a generated ID
db.collection("users")
    .add(user)
    .addOnSuccessListener { documentReference ->
        Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "Error adding document", e)
    }

Java

// Create a new user with a first, middle, and last name
Map<String, Object> user = new HashMap<>();
user.put("first", "Alan");
user.put("middle", "Mathison");
user.put("last", "Turing");
user.put("born", 1912);

// Add a new document with a generated ID
db.collection("users")
        .add(user)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
            }
        });

Đọc dữ liệu bằng các thao tác Core

Sử dụng trình xem dữ liệu trong bảng điều khiển của Firebase để nhanh chóng xác minh rằng bạn đã thêm dữ liệu vào Cloud Firestore.

Bạn cũng có thể dùng phương thức "get" để truy xuất toàn bộ tập hợp.

Web

import { collection, getDocs } from "firebase/firestore"; 

const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
  console.log(`${doc.id} => ${doc.data()}`);
});

Web

db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});
Swift
Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
do {
  let snapshot = try await db.collection("users").getDocuments()
  for document in snapshot.documents {
    print("\(document.documentID) => \(document.data())")
  }
} catch {
  print("Error getting documents: \(error)")
}

Kotlin

db.collection("users")
    .get()
    .addOnSuccessListener { result ->
        for (document in result) {
            Log.d(TAG, "${document.id} => ${document.data}")
        }
    }
    .addOnFailureListener { exception ->
        Log.w(TAG, "Error getting documents.", exception)
    }

Java

db.collection("users")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.w(TAG, "Error getting documents.", task.getException());
                }
            }
        });

Đọc dữ liệu bằng các thao tác trong quy trình

Giờ đây, bạn có thể so sánh trải nghiệm truy vấn Pipeline với trải nghiệm truy vấn Core.

Web

// The import/require of "firebase/firestore/pipelines" has a side-effect
// of extending the Firestore class with the `.pipeline()` method.
// Without this import/require, you will not be able to create a Pipeline.
// import { execute } from "firebase/firestore/pipelines";
const readDataPipeline = db.pipeline()
  .collection("users");

// Execute the pipeline and handle the result
try {
  const querySnapshot = await execute(readDataPipeline);
  querySnapshot.results.forEach((result) => {
    console.log(`${result.id} => ${result.data()}`);
  });
} catch (error) {
    console.error("Error getting documents: ", error);
}
Swift
do {
  // Initialize a Firestore Pipeline instance and specify the "users" collection as the
  // input stage.
  let snapshot = try await db.pipeline()
    .collection("users")
    .execute() // Execute the pipeline to retrieve documents.

  // Iterate through the documents in the pipeline results, similar to a regular query
  // snapshot.
  for result in snapshot.results {
    print("\(result.id ?? "no ID") => \(result.data)")
  }
} catch {
  print("Error getting documents with pipeline: \(error)")
}

Kotlin

val readDataPipeline = db.pipeline()
    .collection("users")

// Execute the pipeline and handle the result
readDataPipeline.execute()
    .addOnSuccessListener { result ->
        for (document in result) {
            println("${document.getId()} => ${document.getData()}")
        }
    }
    .addOnFailureListener { exception ->
        println("Error getting documents: $exception")
    }

Java

Pipeline readDataPipeline = db.pipeline()
.collection("users");

readDataPipeline.execute()
.addOnSuccessListener(new OnSuccessListener<Pipeline.Snapshot>() {
    @Override
    public void onSuccess(Pipeline.Snapshot snapshot) {
        for (PipelineResult result : snapshot.getResults()) {
            System.out.println(result.getId() + " => " + result.getData());
        }
    }
})
.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        System.out.println("Error getting documents: " + e);
    }
});

Bảo mật dữ liệu cho SDK di động và web

Nếu bạn đang sử dụng SDK của nền tảng web, Android hoặc Apple, hãy sử dụng Xác thực FirebaseCloud Firestore Security Rules để bảo mật dữ liệu của bạn trong Cloud Firestore.

Dưới đây là một số bộ quy tắc cơ bản mà bạn có thể sử dụng để bắt đầu. Bạn có thể sửa đổi các quy tắc bảo mật trong thẻ Quy tắc của bảng điều khiển.

Cần có quyền truy cập

// Allow read/write access to a document keyed by the user's UID
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow read, write: if request.auth != null && request.auth.uid == uid;
    }
  }
}

Chế độ sản xuất

// Deny read/write access to all users under any conditions
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

Trước khi triển khai ứng dụng web, Android hoặc iOS vào quy trình sản xuất, hãy thực hiện các bước để đảm bảo rằng chỉ các ứng dụng khách của bạn mới có thể truy cập vào dữ liệu Cloud Firestore. Xem tài liệu về App Check.

Nếu bạn đang sử dụng một trong các SDK máy chủ, hãy dùng Quản lý danh tính và quyền truy cập (IAM) để bảo mật dữ liệu của bạn trong Cloud Firestore.

Các bước tiếp theo

Nâng cao kiến thức về các hoạt động của Core và Pipeline qua các chủ đề sau: