Cmag
Cmag

Reputation: 15760

Parent Entities, nodejs

Folks, How does one access the parent entities? Lets imagine I have 2 Kinds, users and say cars... When Kind cars is queried by plate, it returns all the entities that match the plate. How can one also get those entities' ancestor information? What if I wanted to get the parent key for the returned' entities? Is this possible?

Example where I only am able to retrieve the entities

const query = datastoreClient.createQuery('cars')
    .filter('plate', '=', 'ABC');
return datastoreClient.runQuery(query).then(function (entities) {
    console.log(entities);
    return entities;
});

output:

[
    [
        {
            "id": "2b49ca40-a5fb-11e7-ad5c-c95aa76161c6",
            "plate": "ABC"
        }
    ],
    {
        "moreResults": "NO_MORE_RESULTS",
        "endCursor": "Cn0Sd2oWc35za2lsZnVsLWZyYW1lLTE4MDIxN3JdCxIFdXNlcnMiJDIxMmU2MTQwLWE1OTQtMTFlNy1iMGQ1LWUxNjBjMjA0NjI2MQwLEgRjYXJzIiQyYjQ5Y2E0MC1hNWZiLTExZTctYWQ1Yy1jOTVhYTc2MTYxYzYMGAAgAA=="
    }
]

Upvotes: 0

Views: 265

Answers (1)

Yurci
Yurci

Reputation: 576

Here you have the Node.js code that does what you want:

const Datastore = require('@google-cloud/datastore');
const projectId = 'some-projectid'

// Creates a client
const datastore = new Datastore({
  projectId: projectId,
});

const Query = datastore
        .createQuery('cars')
        .filter('plate', '=', 'some-plate-number')

datastore.runQuery(Query).then(results => {
  // Task entities found.
  const tasks = results[0];
  console.log('Tasks:');
  tasks.forEach(task => console.log(task));

Output:

Tasks: { plate: 'some-plate-number', [Symbol(KEY)]: Key { namespace: undefined, id: 'id-of-the-child-entity', kind: 'cars', parent: Key { namespace: undefined, id: 'id-of-the-parent-entity', kind: 'users', path: [Getter] }, path: [Getter] } }

Upvotes: 1

Related Questions