简体   繁体   中英

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

Whenever I run the function it will just run until it crashes stating the error is unknown. I feel it may be something to do with the version of the datastore dependency in my package.json file

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

I've resorted to simply seeing if the entity is null because nothing else seems to be working

I think you're missing the Kind in the get

I created a Dog Kind and added Freddie to it and can:

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 If your Datastore is in the same project, you can use Application Default Credentials to simplify the auth, ie const datastore = new Datastore();

Can you try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM