无法使用 node.js 通过 Google 云函数访问数据存储

Can't access Datastore through Google Cloud function using node.js

每当我 运行 函数时,它只会 运行 直到它崩溃并指出错误未知。我觉得这可能与我的 package.json 文件

中数据存储依赖项的版本有关

package.json

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

index.js

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */

// Requested from front end
var date = "2002-09-13";
var limit = "10";

exports.checkRecords = async (req, res) => {
  // Search for date in Datastore
    const {Datastore} = require('@google-cloud/datastore');
    const datastore = new Datastore({
        projectId: '...',
        keyFilename: '...'
    });

    const taskKey = datastore.key('headline');
    const [entity] = await datastore.get(taskKey);

    if(entity != null){
      res.status(200).send("contains");
    }
    else{
      res.status(200).send("null");
    }
};

我已经求助于简单地查看实体是否为 null,因为其他方法似乎都不起作用

我认为您缺少 get

中的 Kind

我创建了一个 Dog 种类并添加了 Freddie 并且可以:

var date = "2002-09-13";
var limit = "10";

exports.checkRecords = async (req, res) => {
    const { Datastore } = require("@google-cloud/datastore");
    const datastore = new Datastore();
    const taskKey = datastore.key(["Dog", "Freddie"]);
    const [entity] = await datastore.get(taskKey);

    if (entity != null) {
        res.status(200).send("contains");
    }
    else {
        res.status(200).send("null");
    }
};

NB 如果你的 Datastore 在同一个项目中,你可以使用 Application Default Credentials 来简化授权,即 const datastore = new Datastore();

你能试试吗:

var date = "2002-09-13";
var limit = "10";

exports.checkRecords = async (req, res) => {
  // Search for date in Datastore
    const {Datastore} = require('@google-cloud/datastore');
    const datastore = new Datastore({
        projectId: '...',
        keyFilename: '...'
    });

    // The kind of the entity
    const kind = 'Task';

    // The name/ID of the entity
    const name = 'sampletask1';

    // The Cloud Datastore key for the new entity
    const taskKey = datastore.key([kind, name]);
    const [entity] = await datastore.get(taskKey);

    if(entity != null){
      res.status(200).send("contains");
    }
    else{
      res.status(200).send("null");
    }
};