如何使用Google Cloud Function上的Node.js按名称返回整个数据存储区表

时间:2019-03-28 00:06:30

标签: google-cloud-platform google-cloud-datastore datastore

我想按名称检索表(包含所有行)。我想在主体{"table": user}上使用类似这样的HTTP请求。

尝试此代码失败:

'use strict';

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

// Instantiates a client
const datastore = new Datastore();

exports.getUsers = (req, res) => {

//Get List
const query = this.datastore.createQuery('users');
this.datastore.runQuery(query).then(results => {
  const customers = results[0];
  console.log('User:');
  customers.forEach(customer => {
    const cusKey = customer[this.datastore.KEY];
    console.log(cusKey.id);
    console.log(customer);
  });
})
.catch(err => { console.error('ERROR:', err); });


}

1 个答案:

答案 0 :(得分:0)

Google数据存储区是用于实体而非表的NoSQL数据库。您想要的是加载所有“记录”(它们是数据存储区中的“键标识符”)及其所有“属性”(即您在控制台中看到的“列”)。但是,您想基于“种类”名称(即您所指的“表格”)加载它们。

这是一个解决方案,该解决方案是如何使用在Node.js 8环境中运行的HTTP触发云功能从数据存储中检索所有键标识符及其属性的。

  1. 创建Google Cloud Function并选择HTTP触发器。
  2. 选择运行时为Node.js 8
  3. 在index.js中,将所有代码替换为this GitHub code
  4. 在package.json中添加:
    {
      "name": "sample-http",
      "version": "0.0.1",
      "dependencies": {
        "@google-cloud/datastore": "^3.1.2"
      }
    }
  1. 要执行的功能下,添加loadDataFromDatastore,因为这是我们要执行的功能的名称。
  

注意:这会将所有已加载的记录记录到Stackdriver日志中   云功能。每条记录的响应是一个JSON,   因此您必须将响应转换为JSON对象   获取所需的数据。明白想法并相应地修改代码。