【问题标题】:Finding random (auto) id assigned to our document by Firestore查找 Firestore 分配给我们文档的随机(自动)ID
【发布时间】:2021-08-01 22:43:06
【问题描述】:

我知道这是一个有点奇怪的问题,但是我如何在创建新文档时访问 google firebase 为我的文档生成的唯一(自动)ID。例如这是我的代码

val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
postCollections.document().set(newPost)

我怎么知道为这个“newPost”文档生成的 id 是什么,因为我想在我的代码中使用该 id,同时我不想发送自定义 id,因为它不是唯一的

【问题讨论】:

  • 我不想发送自定义 ID,因为它不是唯一的 为什么?使用 UUID。

标签: java firebase kotlin google-cloud-firestore


【解决方案1】:
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
postCollections.document().set(newPost)

您可能已经发现,.set() 返回一个Promise <void>

但是您忽略的是 .set() 仅在 DocumentReference 上运行 - 这是您从 postCollections.document() 获得的。 DocumentReference 具有属性 idpath - 它是 .document() 创建一个新的、唯一的 documentId。

所以:

val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
val newRef = postCollections.document()
newRef.set(newPost)

现在您可以将文档 ID(和路径)用作 newRef 的属性。

https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference

【讨论】:

  • 我会注意到这样的 id 是非常无用的,除了创建一个独特的子文档之类的任务。很难搜索/查询其他问题。最好对文档进行结构化,以便查询 data 而不是 ids
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2021-07-02
  • 2021-04-12
  • 2020-08-10
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
相关资源
最近更新 更多