8
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cloud DatastoreでKeyのIDを取得する方法

Last updated at Posted at 2018-05-15

背景/目的

Cloud Datastoreを利用している際にIDを自動生成したあと、Queryで取得したエンティティのKeyのIDがほしかったのだが、アクセスするための情報がなかなか見つからなからず苦労したので忘れないうちにメモをしておく。

結論

公式の Datastore メタデータ に記載されているが以下のように entity[datastore.KEY].id とするとKeyのIDの取得ができる。

sample.js
const Datastore = require('@google-cloud/datastore');

const projectId = 'YOUR_PROJECT_ID';

const datastore = new Datastore({
  projectId: projectId,
});

const kind = 'Task';

const taskKey = datastore.key([kind]);

const data = {
  category: 'Personal',
  done: false,
  priority: 4,
  description: 'Learn Cloud Datastore',
};

const task = {
  key: taskKey,
  data: data,
};

datastore
  .save(task)
  .then(() => {
    console.log(`Saved ${task.key.id}: ${task.data.description}`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

const query = datastore
  .createQuery('Task')
  .filter('done', '=', false);

datastore.runQuery(query)
  .then(results => {
    const tasks = results[0];

    console.log('Tasks ID:');
    tasks.forEach(task => console.log(task[datastore.KEY].id)); // <= IDの取得
  });

コレで次からはKeyのID/Nameが欲しくなっても大丈夫。

8
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?