auto generate id for document and not collection in firestore

Now that v9 of the firebase javascript API is out the syntax has changed a little.

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

// Add a new document with a generated id.
const docRef = await addDoc(collection(db, "cities"), {
  name: "Tokyo",
  country: "Japan"
});
console.log("Document written with ID: ", docRef.id);

You can wrap it in a try/catch block to handle errors.

In summary:

  • If you want to auto generate an ID use addDoc() + collection()
  • If you want to set the ID use setDoc() + doc()

This answer might be a little late but you can look at this code here which will generate a new document name:

// Add a new document with a generated id.
db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});

it's more convenient to let Cloud Firestore auto-generate an ID for you. You can do this by calling add()

Read more about it on Add data to Cloud Firestore


If you are using CollectionReference's add() method, it means that it:

Adds a new document to this collection with the specified POJO as contents, assigning it a document ID automatically.

If you want to get the document id that is generated and use it in your reference, then use DocumentReference's set() method:

Overwrites the document referred to by this DocumentRefere

Like in following lines of code:

String id = db.collection("collection_name").document().getId();
db.collection("collection_name").document(id).set(object);