问题
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.
- Create a Google Cloud Function and choose the trigger to HTTP.
- Choose the runtime to be Node.js 8
- In index.js replace all the code with this GitHub code.
- In package.json add:
{
"name": "sample-http",
"version": "0.0.1",
"dependencies": {
"@google-cloud/datastore": "^3.1.2"
}
}
- 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