auto generate id for document and not collection in firestore

喜夏-厌秋 提交于 2020-02-05 05:17:08

问题


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)

回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/52900318/auto-generate-id-for-document-and-not-collection-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!