Is there any chance to add a document to firestore collection with custom generated id, not the id generated by firestore engine?
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.
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.
You cannot have several documents with the same ID in one Collection: a document ID must be unique across a collection.
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"});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With