Create a Firestore document reference with an autogenerated id

Create a Firestore document reference with an autogenerated id

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

Go

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

Java

// 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

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

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

PHP

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

Python

new_city_ref = db.collection(u'cities').document()

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

Ruby

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.