如何在Google Cloud Function上使用Node.js按名称返回整个数据存储区表 [英] How to return an entire Datastore table by name using Node.js on a Google Cloud Function

查看:54
本文介绍了如何在Google Cloud Function上使用Node.js按名称返回整个数据存储区表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to retrieve a table (with all rows) by name. I want to HTTP request using something like this on the body {"table": user}.

尝试此代码失败:

'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); });


}

推荐答案

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

Google Datastore is a NoSQL database that is working with entities and not tables. What you want is to load all the "records" which are "key identifiers" in Datastore and all their "properties", which is the "columns" that you see in the Console. But you want to load them based the "Kind" name which is the "table" that you are referring to.

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

Here is a solution on how to retrieve all the key identifiers and their properties from Datastore, using HTTP trigger Cloud Function running in Node.js 8 environment.

  1. 创建Google Cloud Function并选择HTTP触发器.
  2. 选择运行时为Node.js 8
  3. 在index.js中,将所有代码替换为该GitHub代码.
  4. 在package.json中添加:

    {
      "name": "sample-http",
      "version": "0.0.1",
      "dependencies": {
        "@google-cloud/datastore": "^3.1.2"
      }
    }

  1. 要执行的功能下,添加 loadDataFromDatastore ,因为这是我们要执行的功能的名称.
  1. Under Function to execute add loadDataFromDatastore, since this is the name of the function that we want to execute.

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

NOTE: This will log all the loaded records into the Stackdriver logs of the Cloud Function. The response for each record is a JSON, therefore you will have to convert the response to a JSON object to get the data you want. Get the idea and modify the code accordingly.

这篇关于如何在Google Cloud Function上使用Node.js按名称返回整个数据存储区表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆