Node.JS Datastore Query get Key

大城市里の小女人 提交于 2019-12-01 15:25:08

问题


How can I get the key of an entity returned by a query?

I tried to access it like the normal data, but when I print the entity itself there is no key. Is there even a way to do so?

Thank you in advance for your help.


回答1:


Since version 0.5.0 of the @google-cloud/datastore v0.5.0 the key is now accesible by a Symbol.

var datastore = require('@google-cloud/datastore')();
var query = datastore.createQuery('AnimalNamespace', 'Lion');
query.run(function(err, entities) {

var keys = entities.map(function(entity) {
        // datastore.KEY is a Symbol
        return entity[datastore.KEY];
    });
});

You could also use the gstore-node library (https://github.com/sebelga/gstore-node) and then you would access it directly by entity.entityKey




回答2:


According to the documentation, datastore.runQuery returns a entity objects, with the properties data and key. You are interested in key.

datastore.runQuery(query, function(err, entities) {
  // entities = [
  //   {
  //     data: The record,
  //     key: The key for this record
  //   },
  //   ...
  // ]
});

So, for example using the first entity, you would access the key like this:

entity = entities[0]
key = entity.key


来源:https://stackoverflow.com/questions/40268394/node-js-datastore-query-get-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!