Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 485
Harvey Dent Avatar asked Oct 04 '22 13:10

Harvey Dent


People also ask

How do I add a document to a specific ID in firestore?

Set the data of a document within a collection, explicitly specifying a document identifier. Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier. Create an empty document with an automatically generated identifier, and assign data to it later.

How do I add unique data to firestore?

Yes, this is possible using a combination of two collections, Firestore rules and batched writes. The simple idea is, using a batched write, you write your document to your "data" collection and at the same write to a separate "index" collection where you index the value of the field that you want to be unique.

Can two documents have the same ID in firestore?

You cannot have several documents with the same ID in one Collection: a document ID must be unique across a collection.


2 Answers

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

like image 335
Finlay Percy Avatar answered Oct 19 '22 10:10

Finlay Percy


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"});
  }
}
like image 23
Papa Kojo Avatar answered Oct 19 '22 10:10

Papa Kojo