javascript - 在 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",
});
解决方案
为了澄清这些方法之间的差异:
.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})
推荐阅读
- python - 使用布尔值而不是带有“if”语句的 int 是否有好处
- image - 从 url/http 下载并打开图片 [Android Xamarin App]
- python - 获取与每行python的id对应的值
- python - Dagster 在配置模式中传递有序字典
- ms-word - TINYMCE - 粘贴插件:如何从 Word 文档中修改样式
- visual-studio-code - 在 Visual Studio 代码中选项卡时插入“真实”空格
- google-sheets - 如果左侧单元格符合特定条件,如何计算右侧单元格中的值
- java - 找不到参数的方法 classpath() [com.android.tools.build:gradle:4.1.3]
- python - 创建了两个共享 x 轴的图:第二个图被切断
- bash - 别名的 Git 补全就像 Git 本身一样