问题描述
我已经阅读了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
我经常看到的是:
collection
|--{auto-generated-id}
|--property1:value1
|--property2:value2
|--peoperty3:value3
在前者中,我无法在文档上调用 add()
-(生成唯一ID).但是,这可以在集合中完成,如上面的后一个草图所示.
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.
因此,我的问题是:Firestore有没有一种方法可以在创建文档后帮助自动生成IDIE我如何实现这样的目标:
My question is thus:Is there a way firestore can help autogenerate an id after creating a documenti.eHow can I achieve something like this:
db.collection("collection_name").document("document_name").add(object)
推荐答案
如果您使用的是CollectionReference的 add()方法,这意味着它:
If you are using CollectionReference's add() method, it means that it:
如果您要获取生成的文档ID并在参考中使用它,请使用DocumentReference的 set()方法:
If you want to get the document id that is generated and use it in your reference, then use DocumentReference's set() method:
就像下面的代码行一样:
Like in following lines of code:
String id = db.collection("collection_name").document().getId();
db.collection("collection_name").document(id).set(object);
这篇关于自动为文档生成ID,而不是在Firestore中生成ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!