Lucifer
Lucifer

Reputation: 1079

How do we get the unique IDs when returning data from the query

I am using GCP Datastore as a database. When I initialized the data I gave an image name as ID, still, it created a column Name/ID with unique Ids. But, when I try to return data by query it is only returning ID given by me. I need to get the auto-generated IDs also.

enter image description here

This is the code I'm using to query the entity.

var query = datastore.createQuery(['Defects']).filter('isProcessed', '=', false).filter('companyId', '=', id);

datastore.runQuery(query, (err, books) => callback(err, books, datastore.KEY));

Upvotes: 1

Views: 627

Answers (2)

Joan Grau Noël
Joan Grau Noël

Reputation: 3192

Datastore is a NoSQL database, and it uses unique ID's for each entity, which are automatically generated if not specified by you.

The problem is that you are returning datastore.KEY, which has the following fields:

Key {
  namespace: undefined,
  id: '1234567890',
  kind: 'My-Entity-Kind',
  path: [Getter] 
}

So reading the "id" field of the datastore.KEY object will give you the entity unique ID.

I did a quick example to show how to get the id in a similar example to yours:

const Datastore = require('@google-cloud/datastore');
const datastore = new Datastore();

var query = datastore.createQuery('My-Entity-Kind');

query.run((err, entities) => {
  const keys = entities.map((entity) => {
    var temp_entity = entity[datastore.KEY];

    // Save the id from the entity Key in a variable
    var entity_id = console.log(temp_entity["id"])

    // Print whole entity.KEY structure
    console.log(temp_entity)
    // Print only the entity id
    console.log(entity_id)
    // Print a random property
    console.log(entity["entity-property"]);

    return entity[datastore.KEY];
  });
});

Upvotes: 1

Caner
Caner

Reputation: 59198

Try this:

books[0][datastore.KEY]['id']

Upvotes: 0

Related Questions