Auto Generate Id For Document And Not Collection In Firestore


Answer :

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); 

Since you already know the id of the document, just call set() instead of add(). It will create the document if it doesn't already exist.


This answer might be a little late but you can look at this code here which will generate a new document name:

// Add a new document with a generated id. db.collection("cities").add({     name: "Tokyo",     country: "Japan" }) .then(function(docRef) {     console.log("Document written with ID: ", docRef.id); }) .catch(function(error) {     console.error("Error adding document: ", error); }); 

it's more convenient to let Cloud Firestore auto-generate an ID for you. You can do this by calling add()

Read more about it on Add data to Cloud Firestore


Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Change The Font Size Of Visual Studio Solution Explorer