添加数据

本文档介绍如何在 Cloud Firestore 中设置、添加或更新单个文档。如需批量写入数据,请参阅事务和批量写入。

概览

您可以通过以下任一方式将数据写入 Cloud Firestore:

  • 设置集合中的文档的数据,明确指定文档标识符。
  • 向集合添加新文档。在这种情况下,Cloud Firestore 会自动生成文档标识符。
  • 创建一个使用自动生成的标识符的空文档,并在以后向该文档分配数据。

须知事项

在初始化 Cloud Firestore 以设置、添加或更新数据之前,您必须完成以下步骤:

  • 创建 Cloud Firestore 数据库。如需了解详情,请参阅 Cloud Firestore 使用入门
  • 如果您使用的是 Web 或移动客户端库,请使用安全规则进行身份验证。如需了解详情,请参阅安全规则使用入门。
  • 如果您使用的是服务器客户端库或 REST API,请使用 Identity and Access Management (IAM) 进行身份验证。如需了解详情,请参阅服务器客户端库的安全性。

初始化 Cloud Firestore

初始化 Cloud Firestore 的实例:

移动 SDK 和 Web SDK

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);

// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);

将 FIREBASE_CONFIGURATION 替换为 Web 应用的 firebaseConfig。

如需在设备的网络连接中断时保留数据,请参阅启用离线数据文档。

Web

import firebase from "firebase/app";
import "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
firebase.initializeApp(firebaseConfig);

// Initialize Cloud Firestore and get a reference to the service
const db = firebase.firestore();

将 FIREBASE_CONFIGURATION 替换为 Web 应用的 firebaseConfig。

如需在设备的网络连接中断时保留数据,请参阅启用离线数据文档。

Swift

注意:此产品不适用于 watchOS 和 App Clip 目标。

import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()

AppDelegate.swift
Objective-C

注意:此产品不适用于 watchOS 和 App Clip 目标。

@import FirebaseCore;
@import FirebaseFirestore;

// Use Firebase library to configure APIs
[FIRApp configure];
FIRFirestore *defaultFirestore = [FIRFirestore firestore];

AppDelegate.m

Kotlin

// Access a Cloud Firestore instance from your Activity
val db = Firebase.firestore

DocSnippets

.kt