自动为文档生成ID,而不是在Firestore中生成ID [英] auto generate id for document and not collection in firestore

查看:48
本文介绍了自动为文档生成ID,而不是在Firestore中生成ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了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 document i.e How can I achieve something like this:

db.collection("collection_name").document("document_name").add(object)

推荐答案

如果您使用的是CollectionReference的

If you are using CollectionReference's add() method, it means that it:

使用指定的POJO作为内容向此集合添加一个新文档,并自动为其分配一个文档ID.

Adds a new document to this collection with the specified POJO as contents, assigning it a document ID automatically.

如果您要获取生成的文档ID并在参考中使用它,请使用DocumentReference的

If you want to get the document id that is generated and use it in your reference, then use DocumentReference's set() method:

覆盖此DocumentRefere引用的文档

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

这篇关于自动为文档生成ID,而不是在Firestore中生成ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆