trollkotze
trollkotze

Reputation: 1139

How to do a "keys-only-query" in Google Cloud Datastore (Node.js)

I am trying to do a "keys-only query" with Google Datastore API for Node.js, as exemplified in the documentation here.

I do that after having saved a number of records like this:

datastore.save(
  records.map(
    (record) => {
      return {
        key: datastore.key([kind, record.id]),
        data: record,
      };
    }
  )

The constant kind is a string. Each record has a valid unique id property (a number), which, as shown here, should also serve as the datastore key identifier.

The records are stored correctly. I can retrieve them all without problems through

datastore.runQuery(datastore.createQuery(kind))
.then( (results) => {
    // whatever...
}

All the saved records are returned correctly.

But when I do a "keys-only query" like this (and as exemplified in the documentation):

const query = datastore.createQuery(kind)
  .select('__key__');
datastore.runQuery(query)
.then( (results) => {
    // whatever...
}

my results[0] return value is simply an array of empty objects like this:

results[0]: [ {}, {}, {}, {}, {}, ..., {}]

The number of empty objects returned here is the correct number of records of the given kind. But the problem is that they are empty objects. I expected to get the datastore key for each record here.

If, on the other hand, I do a "normal" projection query, on a "normal" property (like "id" - which should be identical with the datastore key, as far as I understand, after having defined the key through datastore.key[kind, record.id]), I retrieve the projected "id" properties correctly thus:

const query = datastore.createQuery(kind)
  .select('id');
datastore.runQuery(query)
.then( (results) => {
    // whatever...
}

Result:

results[0]: [ 
  { id: 5289385927 },
  { id: 5483575687 },
  { id: 5540575111 },
  { id: 5540622279 },
  // ... and so on
]

So what is wrong with my "keys-only-query"? I have done it exactly in the way the documentation describes. But I get only empty results.

NOTE: I have tested this only in Datastore emulator. Same result in Datastore Emulator as in AppEngine.

Upvotes: 9

Views: 3365

Answers (1)

Gamec
Gamec

Reputation: 414

The objects are not empty but contain only datastore keys, which are stored under a symbol property: datastore.KEY. In javascript, symbol properties might not output by default.

You can get entity key using symbol datastore.KEY

var keys = results.map(function(res) {
     return res[datastore.KEY];
});

Upvotes: 8

Related Questions