Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto generate id for document and not collection in firestore

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)
like image 471
Urchboy Avatar asked Oct 19 '18 21:10

Urchboy


2 Answers

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()
like image 143
pietz Avatar answered Sep 25 '22 08:09

pietz


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);
like image 36
Alex Mamo Avatar answered Sep 25 '22 08:09

Alex Mamo