在交易中获取实体的ID [英] Getting entity's id inside a transaction

查看:128
本文介绍了在交易中获取实体的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据存储事务,在其中创建一个实体(用户),让数据存储为我生成ID.

I have a datastore transaction where I create an entity (a user) letting datastore generate the ID for me.

然后,我想使用该ID,以便我可以创建另一个(另一种)实体.

I then would like to use that ID so that I can create another entity (of another kind).

虽然可以通过常规数据存储区"save" api来实现:

While this is possible with regular datastore 'save' api:

datastore.save(user).then(() => {
  userId = user.key.id // returns entity's ID created by datastore
})

但是,在使用事务时这似乎是不可能的:

However, this does not seem possible when using a transaction:

transaction.save(user).then(() => {
  console.log( user.key.id )
})

上面的输出无法读取未定义的'then''", 即使 docs ,我还是尝试过.

The above outputs "cannot read 'then' of undefined'", even though there's no callback listed in the docs, i tried anyway.

在创建/保存带有交易的实体时,如何获取该实体的自动生成的ID?

When creating/saving an entity with a transaction, how can I retrieve that entity's autogenerated ID?

推荐答案

分配ID

您可以使用方法:projects.allocateIds 进入交易之前:

为给定的键分配ID,这对于在插入实体之前引用实体很有用.

Allocates IDs for the given keys, which is useful for referencing an entity before it is inserted.

使用Python客户端库.

这将使数据存储区保留" ID(即使仍然不会使用这些ID创建任何实体),并避免在插入之前发生ID冲突.

This will make Datastore 'reserve' IDs (even though there still won't be any entities created with those IDs) and avoid ID collision before inserting.

在您的交易中,您将从分配的ID中获得一个ID,并将其分配给第一个实体.然后,即使在事务提交第一个实体插入之前,您也可以在第二个实体中引用相同的ID.

Inside your transaction, you get one ID from those allocated and assign to the first entity. Then you can reference the same ID in your second entity, even before the transaction committed the first entity insert.

交易的最长持续时间为60秒,30秒后有10秒的闲置到期时间.

Transactions have a maximum duration of 60 seconds with a 10 second idle expiration time after 30 seconds.

因此,最佳做法是在进行交易之前尽一切可能.当然,分配ID是您在交易前可以运行的功能之一.

Because of that, the best practice is performing everything possible before entering your transaction. Allocate IDs is, of course, one of the things you can run before your transaction.

这篇关于在交易中获取实体的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆