Create a Firestore document reference with an autogenerated id

Create a Firestore document reference with an autogenerated id

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

To authenticate to Firestore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

DocumentReference addedDocRef = db.Collection("cities").Document();
Console.WriteLine("Added document with ID: {0}.", addedDocRef.Id);
await addedDocRef.SetAsync(city);

Go

To authenticate to Firestore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import (
	"context"
	"log"

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

func addDocAfterAutoGeneratedID(ctx context.Context, client *firestore.Client) error {
	data := City{
		Name:    "Sydney",
		Country: "Australia",
	}

	ref := client.Collection("cities").NewDoc()

	// later...
	_, err := ref.Set(ctx, data)
	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

To authenticate to Firestore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// Add document data after generating an id.
DocumentReference addedDocRef = db.collection("cities").document();
System.out.println("Added document with ID: " + addedDocRef.getId());

// later...
ApiFuture<WriteResult> writeResult = addedDocRef.set(data);

Node.js

To authenticate to Firestore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const newCityRef = db.collection('cities').doc();

// Later...
const res = await newCityRef.set({
  // ...
});

PHP

To authenticate to Firestore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

$addedDocRef = $db->collection('samples/php/cities')->newDocument();
printf('Added document with ID: %s' . PHP_EOL, $addedDocRef->id());
$addedDocRef->set($data);

Python

To authenticate to Firestore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

new_city_ref = db.collection("cities").document()

# later...
new_city_ref.set(
    {
        # ...
    }
)

Ruby

To authenticate to Firestore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

cities_ref = firestore.col collection_path

added_doc_ref = cities_ref.doc
puts "Added document with ID: #{added_doc_ref.document_id}."

added_doc_ref.set data

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.