Getting entity's id inside a transaction

别等时光非礼了梦想. 提交于 2019-12-11 03:47:46

问题


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

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

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

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

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


回答1:


Allocate IDs

You can use Method: projects.allocateIds before entering the transaction:

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

Using the Python client library.

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.

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.

Best practice for transactions

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

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.



来源:https://stackoverflow.com/questions/43384636/getting-entitys-id-inside-a-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!