How to return an entire Datastore table by name using Node.js on a Google Cloud Function

纵饮孤独 提交于 2020-05-17 09:27:05

问题


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}.

Tried this code without success:

'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:


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.

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. Create a Google Cloud Function and choose the trigger to HTTP.
  2. Choose the runtime to be Node.js 8
  3. In index.js replace all the code with this GitHub code.
  4. In package.json add:
    {
      "name": "sample-http",
      "version": "0.0.1",
      "dependencies": {
        "@google-cloud/datastore": "^3.1.2"
      }
    }
  1. Under Function to execute add loadDataFromDatastore, since this is the name of the function that we want to execute.

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.



来源:https://stackoverflow.com/questions/55388299/how-to-return-an-entire-datastore-table-by-name-using-node-js-on-a-google-cloud

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