我无法弄清楚如何从 Google 数据存储区设置和获取实体数据。我找到了不同的例子,但不明白哪一个是正确的。以下是我到目前为止所做的事情。我不断收到此错误:ReferenceError:数据存储未定义
。我没有正确调用数据存储 api 吗?
server.js 文件:
var express = require('express');
var app = express();
const Datastore = require('@google-cloud/datastore');
const datastore = Datastore();
require('./routes/main')(app);
require('@google/cloud-debug').start({
keyFilename: './jarvis-hd-live-842e4f78479e.json'
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Your app is listening on port ${PORT}`);
});
路线文件:
app.post('/message', function (request, response) {
message = request.body.Body;
response.send("<Response><Message>Heyyo!</Message></Response>");
const key = datastore.key('timestamp');
datastore.save({
key: key,
data : {
timestamp_value: 0
}
});
datastore.insert(entity)
.then(()=> {
console.log("Data object inserted successfully.");
});
});
最佳答案
数据存储 SDK 未使用正确的凭据进行身份验证/初始化。
server.js 应该是 -
var express = require('express');
var app = express();
//The key file is required in a variable. The variable is now a JSON object with the credentials.
var credentials = require('./jarvis-hd-live-842e4f78479e.json');
const Datastore = require('@google-cloud/datastore');
//Initialise the datastore object with the proper project id and credentials.
const datastore = Datastore({
projectId: "your_project_id_goes_here",
credentials: credentials
});
/*
* If you wish to give the filename instead of the credentials object while initialising, replace the credential key with keyFileName and the value with the file name of the key file.
* Note: The key file should be in the same directory. If another directory, please provide absolute path.
*/
require('./routes/main')(app);
require('@google/cloud-debug').start({
credentials: credentials
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Your app is listening on port ${PORT}`);
});
在同一行中,routes.js 将如下所示 -
app.post('/message', function (request, response) {
message = request.body.Body;
response.send("<Response><Message>Heyyo!</Message></Response>");
//While getting a key for an object, you need to mention the namespace on which your kind resides.(Kind can be thought of as a table.)
const key = datastore.key({
namespace: "your_namespace_goes_here",
path: ["kind_name_goes_here","explicit_name/id_of_the_object"]
});
/*
* If the name/id is kept null in the path key, datastore will assign a numeric id to the key.
* The name should be set if the application uses some kind of custom naming/identification scheme using UUID/GUID.
*/
datastore.save({
key: key,
data : {
timestamp_value: 0
}
});
datastore.insert(entity)
.then(()=> {
console.log("Data object inserted successfully.");
});
});
关于node.js - 如何使用 Node 设置和接收 Google Datastore 中的实体数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41006168/