sqram
sqram

Reputation: 7201

Datastore get last inserted id with Node

How does one get the last inserted entity's ID in datastore using node?

Doc says to insert like this:

datastore.insert(entity)
  .then(result) => {
    // Task inserted successfully.
  });

From this, inspecting the returned result object, the only way i found was going through the object like this

result[0].mutationResults[0].key.path[0].id

This seems brittle and unreliable. If in the future the structure of the returned object breaks, the app breaks.

Is this the right way to do it in node?

Upvotes: 2

Views: 704

Answers (1)

sqram
sqram

Reputation: 7201

I believe I may have answered my own question.

Inside the then callback, I indeed have to do result[0].mutationResults[0].key.path[0].id

However, I can target the entity as well, like so

const userEntity = {
  email: '[email protected]',
  passwd: 'secret'
}

ds.insert(userEntity)
  .then(result) => {
    return userEntity.key.id
    // or, result[0].mutationResults[0].key.path[0].id
  }

Upvotes: 2

Related Questions