How to add Document with Custom ID to firestore

Is there any chance to add a document to firestore collection with custom generated id, not the id generated by firestore engine?


To use a custom ID you need to use .set, rather than .add

This creates a document with the ID "LA":

db.collection("cities").doc("LA").set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
})

This is taken from the official docs here


In case if you are using angularfire,

class Component{
  constructor(private afs: AngularFireStore) {} // imported from @angular/fire/firestore

  addItem() {
    this.afs.collection('[your collection]').doc('[your ID]').set({your: "document"});
  }
}

To expand on the accepted answer, if you ever wanted your client to generate a random ID for the doc before pushing to Firestore (assuming the same createId() function exists outside of AngularFire2)

const newId = db.createId();
db.collection("cities").doc(newId).set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
})

This is useful for setting the ID as a reference field in another document, even before Firestore saves anything. If you don't need to use the saved object right away, this speeds up the process by not making you wait for the ID. The set() call is now asynchronous from the pipe you might be using in Angular

Notice I didn't put id: newId in the set object, because Firestore by default doesn't save ID as a field in the doc