首页 > 解决方案 > 在 React 或 Javascript 中,我们如何为 Google Cloud Firestore 提供自定义文档 ID

问题描述

我正在使用带有云 Firestore 的 React 我正在尝试添加我自己的文档 ID,而不是自动生成的文档 ID。如果我们不能这样做,有没有办法通过回调来获取提交数据时创建的文档 id?

firebase.firestore()
.collection("user5d")
.document("custom-id")
.add({
    urn: randomNumber,
    line1: "some text",
    line2: "line 2 text",
    slashColor: "green",
    textColor: "white",
  });

标签: javascriptgoogle-cloud-firestore

解决方案


为了澄清这些方法之间的差异:

.add() -> 在集合中添加一个具有自动生成的文档 ID 的文档。您只能在一个上使用它CollectionReference。例如:

firebase.firestore().collection("colName").add({...})

.set() -> 在集合中创建一个新文档,但与.set() 不同的.add()是,您需要指定文档 ID。这个方法只能在一个上调用DocumentReference。例如:

firebase.firestore().collection("colName").doc("docID").set({...})

.update() -> 更新集合中的现有文档。您需要指定文档 ID。与 类似.set(),此方法只能在 aDocumentReference上调​​用。例如:

firebase.firestore().collection("colName").doc("docID").update({...})

您也可以使用它.set()来更新文档,但它会覆盖其余字段,除非您在SetOptions中指定合并属性,例如.set({...}, {merge: true})


推荐阅读