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

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

问题描述

我已经浏览了 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 的 add() 方法,它的意思是:

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 的 set() 方法:

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

就像下面几行代码:

String id = db.collection("collection_name").document().getId();
db.collection("collection_name").document(id).set(object);

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

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