如何从 Google Cloud DataStore 获取自动生成的 ID

How to get auto generated id from Google Cloud DataStore

文档 here 说我可以省略实体的数字 ID,DataStore 会自动分配一个。

但是,它没有说明如何检索自动生成的 ID。如何获得它?

它是否在响应中可用,或者我是否必须针对其他一些字段进行查询以再次检索实体以便我可以看到它的 ID?

会在相应的MutationResult中回复。这是一个 Python 片段,它扩展了 the one in the docs:

req = datastore.CommitRequest()
req.mode = datastore.CommitRequest.NON_TRANSACTIONAL
employee = req.mutation.insert_auto_id.add()

# Request insertion with automatic ID allocation
path_element = employee.key.path_element.add()
path_element.kind = 'Employee'

# ... set properties ...

resp = self.datastore.commit(req)

auto_id_key = resp.mutation_result.insert_auto_id_key[0]

Node 库中,生成的密钥存储在带有 symbol 的查询对象上。数据存储库在 datastore.KEY 上公开此符号,您可以使用它来访问从数据存储检索的实体的 ID/密钥:

// Pseudocode -- you have a handle on the entity from prior list / create operation:
const myEntity = datastore.queryOrListOrCreate();

// actual usage to update it:
const key = myEntity[datastore.KEY];

console.log(JSON.stringify(key));
// prints something like: {"id":"5664922973241322","kind":"myEntity","path":["myEntity","5664922973241322"]}

// use it to e.g. udpate the entity
await datastore.save({
  key,
  data: myEntity,
});

文档没有对此进行解释,因此不确定这是否得到官方认可。