I have gone through the firestore docs and I'm yet to find an example where we have something like this.
collection
|--document
|--{auto-generated-id}
|--property1:value1
|--property2:value2
|--peoperty3:value3
Rather what I often see is:
collection
|--{auto-generated-id}
|--property1:value1
|--property2:value2
|--peoperty3:value3
In the former, I cannot call add()
-(which generates unique id) on a document. However this can be done in a collection as shown in the latter sketch above.
My question is thus: Is there a way firestore can help autogenerate an id after creating a document i.e How can I achieve something like this:
db.collection("collection_name").document("document_name").add(object)
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:
addDoc()
+ collection()
setDoc()
+ doc()
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);
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