11

How can I get the key of an entity returned by a query?

I tried to access it like the normal data, but when I print the entity itself there is no key. Is there even a way to do so?

Thank you in advance for your help.

2 Answers 2

38

Since version 0.5.0 of the @google-cloud/datastore v0.5.0 the key is now accesible by a Symbol.

var datastore = require('@google-cloud/datastore')();
var query = datastore.createQuery('AnimalNamespace', 'Lion');
query.run(function(err, entities) {

var keys = entities.map(function(entity) {
        // datastore.KEY is a Symbol
        return entity[datastore.KEY];
    });
});

You could also use the gstore-node library (https://github.com/sebelga/gstore-node) and then you would access it directly by entity.entityKey

Sign up to request clarification or add additional context in comments.

2 Comments

It worked for me with datastore.Key, and the id is: datastore.Key.id
Why is this the only place on the internet that explains this? No mention of it anywhere in the datastore docs, not even the update examples do this, they always create a new key. Seems absurd that I had to dig up a 5 year old SE question to get such a simple bit of information.... what's up with that?
-4

According to the documentation, datastore.runQuery returns a entity objects, with the properties data and key. You are interested in key.

datastore.runQuery(query, function(err, entities) {
  // entities = [
  //   {
  //     data: The record,
  //     key: The key for this record
  //   },
  //   ...
  // ]
});

So, for example using the first entity, you would access the key like this:

entity = entities[0]
key = entity.key

2 Comments

Unfortunately it returns undefined this way
Please consider answering only when you know what you are talking about... Just scraping some docs and throwing out an answer helps nobody. You have to assume that most people are able to read docs themselves

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.