使用地圖新增 Firestore 文件

使用地圖新增 Firestore 文件

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列文章:

程式碼範例

C#

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

DocumentReference docRef = db.Collection("cities").Document("LA");
Dictionary<string, object> city = new Dictionary<string, object>
{
    { "name", "Los Angeles" },
    { "state", "CA" },
    { "country", "USA" }
};
await docRef.SetAsync(city);

Go

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import (
	"context"
	"log"

	"cloud.google.com/go/firestore"
)

func addDocAsMap(ctx context.Context, client *firestore.Client) error {
	_, err := client.Collection("cities").Doc("LA").Set(ctx, map[string]interface{}{
		"name":    "Los Angeles",
		"state":   "CA",
		"country": "USA",
	})
	if err != nil {
		// Handle any errors in an appropriate way, such as returning them.
		log.Printf("An error has occurred: %s", err)
	}

	return err
}

Java

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Create a Map to store the data we want to set
Map<String, Object> docData = new HashMap<>();
docData.put("name", "Los Angeles");
docData.put("state", "CA");
docData.put("country", "USA");
docData.put("regions", Arrays.asList("west_coast", "socal"));
// Add a new document (asynchronously) in collection "cities" with id "LA"
ApiFuture<WriteResult> future = db.collection("cities").document("LA").set(docData);
// ...
// future.get() blocks on response
System.out.println("Update time : " + future.get().getUpdateTime());

Kotlin

import com.google.api.gax.rpc.ApiException
import com.google.api.gax.rpc.NotFoundException
import com.google.cloud.firestore.FirestoreOptions
import java.util.concurrent.ExecutionException

/**
 * Writes a document with structured fields into a Firestore collection. Setting
 * a document creates the record if it does not exist or overwrites its fields.
 *
 * @param projectId Google Cloud project identifier (for example, "example-project-id").
 * @param collectionId Target Firestore collection identifier (for example, "cities").
 * @param documentId Target Firestore document identifier (for example, "LA").
 */
fun setDocument(projectId: String, collectionId: String, documentId: String) {
  val options =
    FirestoreOptions.getDefaultInstance()
      .toBuilder()
      .setProjectId(projectId)
      .build()

  val documentData =
    mapOf(
      "name" to "Los Angeles",
      "state" to "CA",
      "country" to "USA",
    )

  try {
    options.service.use { firestore ->
      val documentReference =
        firestore.collection(collectionId).document(documentId)
      println("Writing document '$documentId' in collection '$collectionId'...")
      val writeResult = documentReference.set(documentData).get()

      println("Resource ID: ${documentReference.path}")
      println("Collection ID: $collectionId")
      println("Document ID: $documentId")
      println("Update Time: ${writeResult.updateTime}")
    }
  } catch (err: ExecutionException) {
    val message =
      when (val cause = err.cause) {
        is NotFoundException ->
          "error: Firestore database not found in project '$projectId': ${cause.message}"
        is ApiException ->
          "error: failed to write document '$documentId' in collection '$collectionId' for project '$projectId': ${cause.message}"
        else ->
          "error: execution failed while writing document '$documentId' in collection '$collectionId' for project '$projectId': ${err.message}"
      }
    System.err.println(message)
  } catch (err: InterruptedException) {
    Thread.currentThread().interrupt()
    System.err.println(
      "error: interrupted while writing document '$documentId' in collection '$collectionId' for project '$projectId': ${err.message}"
    )
  }
}

Node.js

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

const data = {
  name: 'Los Angeles',
  state: 'CA',
  country: 'USA'
};

// Add a new document in collection "cities" with ID 'LA'
const res = await db.collection('cities').doc('LA').set(data);

PHP

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

$data = [
    'name' => 'Los Angeles',
    'state' => 'CA',
    'country' => 'USA'
];
$db->collection('samples/php/cities')->document('LA')->set($data);

Python

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

data = {"name": "Los Angeles", "state": "CA", "country": "USA"}

# Add a new doc in collection 'cities' with ID 'LA'
db.collection("cities").document("LA").set(data)

Ruby

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

city_ref = firestore.doc "#{collection_path}/LA"

data = {
  name:    "Los Angeles",
  state:   "CA",
  country: "USA"
}

city_ref.set data

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽工具。