![](/img/trans.png)
[英]Firestore: How to insert a document with automatic id while enforcing unique field value?
[英]How to insert document id as a field value Firestore with Go
我想在集合組查詢期間搜索具有特定 ID 的文檔。 根據我的閱讀,直接使用文檔 ID 執行 CGQ 是不可能的,因此我打算在文檔中的字段id
中鏡像文檔的 ID。
我嘗試了firestore.DocumentID
(請參閱下面的代碼片段),希望它作為表示文檔 ID 的標記值(在調用該方法時尚不清楚)。 我發現firestore.DocumentID
實際上是一個值為"__name__"
的常量,它成為結果文檔中id
字段的字符串值。
docRef, _, err := colRef.Add(ctx, map[string]interface{}{
"id": firestore.DocumentID, // this does not work
"events": events,
"url": url,
"enabled": true,
"created": firestore.ServerTimestamp,
"modified": firestore.ServerTimestamp,
})
是否可以在自動調用Add
方法的同時將文檔中的文檔 ID 寫入id
字段?
如果是這樣,那個哨兵值是多少? 如果不是,我是否應該執行先創建文檔然后再用id
字段更新文檔的事務?
您無法告訴 Firestore 客戶端在寫入時插入其新 ID。
要通過單個寫入操作將兩者都寫入數據庫,您必須將新DocumentReference
的創建(這是一個客戶端操作)與實際的數據寫入分開。
所以兩步:
colRef.NewDoc()
創建一個新的DocumentReference
。docRef.Set()
將數據(包括 ID)寫入引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.