【问题标题】:How to get auto generated id from Google Cloud DataStore如何从 Google Cloud DataStore 获取自动生成的 ID
【发布时间】:2019-03-15 03:30:47
【问题描述】:

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

但是,它并没有说明如何检索自动生成的 id。怎么得到?

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

【问题讨论】:

  • 您使用的是哪种语言/ORM/Datastore 库?

标签: google-cloud-platform google-cloud-datastore


【解决方案1】:

它将在响应中对应的MutationResult 中。这是一个在 the one in the docs 上扩展的 Python sn-p:

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]

【讨论】:

    【解决方案2】:

    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,
    });
    
    

    文档没有解释这一点,所以不确定这是否得到官方认可。

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 2020-02-23
      • 2016-05-24
      • 2019-08-12
      相关资源
      最近更新 更多