[英]How to insert document id as a field value Firestore with Go
I would like to search documents with a particular ID during a Collection Group Query.我想在集合组查询期间搜索具有特定 ID 的文档。 From what I have read it is not possible to perform a CGQ using the document ID directly, so I intend to mirror the document's ID in a field id
within the document.根据我的阅读,直接使用文档 ID 执行 CGQ 是不可能的,因此我打算在文档中的字段id
中镜像文档的 ID。
I tried firestore.DocumentID
(see code snippet below) expecting it to serve as a sentinel value representing the document's ID (not yet known at the time the method is called).我尝试了firestore.DocumentID
(请参阅下面的代码片段),希望它作为表示文档 ID 的标记值(在调用该方法时尚不清楚)。 I discovered firestore.DocumentID
is a actually a const with a value of "__name__"
and that becomes a string value of the id
field within the resulting document.我发现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,
})
Is it possible to write the document's ID inside the document to the id
field whilst calling the Add
method atomically?是否可以在自动调用Add
方法的同时将文档中的文档 ID 写入id
字段?
If so, what is that sentinel value?如果是这样,那个哨兵值是多少? If not, should I perform a transaction that first creates the document and then, in turn, updates the document with the id
field?如果不是,我是否应该执行先创建文档然后再用id
字段更新文档的事务?
You can't tell the Firestore client to insert its new ID while writing.您无法告诉 Firestore 客户端在写入时插入其新 ID。
To get both into the database with a single write operation, you'll have to split the creation of the new DocumentReference
(which is a client-side operation) from the actual writing of the data.要通过单个写入操作将两者都写入数据库,您必须将新DocumentReference
的创建(这是一个客户端操作)与实际的数据写入分开。
So two steps:所以两步:
DocumentReference
by calling colRef.NewDoc()
.通过调用colRef.NewDoc()
创建一个新的DocumentReference
。docRef.Set()
.使用docRef.Set()
将数据(包括 ID)写入引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.