Search code examples
node.jsgoogle-app-enginegoogle-cloud-datastoregcloud

Entity key and data properties not defined when retrieving from local datastore


I'm trying to follow along the Googles doc here is the problem I'm facing. According to the doc here when i retrieve an entity like this

var key = datastore.key(['Company', 'Google']);

datastore.get(key, function(err, entity) {
    // entity.data = The record.
    // entity.key = The key.
});

I should get an entity object with the key and data properties. That's not what I'm getting. Here's my read function

function read(kind, id, cb) {
    var key = datastore.key([kind, parseInt(id, 10)]);
    datastore.get(key, (err, entity) => {
    if(err) {
        return cb(err);
    }

    if(!entity) {
        return cb({
            code: 404,
            message: 'Not found'
        });
    }
    cb(null, entity.data);
});
}

Neither data or key are defined. Instead, the retrieved entity looks like this

{
  "age": 23,
  "name": "Hello World"
}

Which obviously is just the data. What am i doing wrong? I'm working on the gcloud datastore emulator

Here are my dependencies if it's relevant

"dependencies": {
    "async": "^2.0.1",
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "google-cloud": "^0.43.0",
    "yargs": "^5.0.0"
 }

Solution

  • Since @google-cloud/datastore v0.5.0 the key is accesible from a Symbol.

    var datastore = require('@google-cloud/datastore')();
    
    var key = datastore.key(['Company', 'Google']);
    
    datastore.get(key, function(err, entity) {
        var key = entity[datastore.KEY];
    });
    

    Of course you could always use gstore-node (disclaimer: I'm the owner of that library) and then you would just access it by entity.entityKey.