Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Sun Apr 16 2023

How to add and get data from Datastore in GCP using NodeJs

In this tutorial, we will take a look at how we can add data to our Datastore, and how to query it. We will use NodeJs for this tutorial, and we will also assume that you have a Datastore enabled at GCP. You can set one up here.

Install datastore

npm i @google-cloud/datastore

Create our DatastoreService.js

Create a file called DatastoreService.js in the root of your project.

Add data

We will start with creating our addData function.

const { Datastore } = require("@google-cloud/datastore"); const datastore = new Datastore(); const addData = async (kind, data) => { const key = datastore.key([kind]); const payload = { key, data: { ...data, timestamp: new Date().toISOString(), }, }; return datastore.save(payload); };

The addData() function will require two arguments, the kind (like the table) of the database, and also the actual data we want to add to the datastore.

Let's try our function. We will create a new kind called employees and add an employee.

(async () => { await addData("employees", { firstName: "Peter", lastname: "Andersson", }); })();
node DatastoreService.js

And if you go to your datastore, there will be a new kind called employees and you should see the data we just added.

datastore

Get data

We will create a function, called getData() and give it three arguments. kind, key and value where key is the field in our data and value is the value we are looking for.

const getData = async (kind, key, value) => { const query = datastore.createQuery(kind).filter(key, "=", value); const data = await datastore.runQuery(query); return data[0]; };

And call it like this:

(async () => { const employees = await getDataFromDatastore( "employees", "firstName", "Peter" ); console.log(employees); })();

That will give us all Peters in our database, in our case it is only one.

[ { "firstName": "Peter", "lastname": "Andersson", "timestamp": "2023-04-14T16:08:25.000Z", ...additionalData } ]

Outro

In this guide we showed how to add data to your datastore in GCP, and then retrieve it again. All done in NodeJs.

I hope you found this tutorial interesting and helpful.

Thanks for reading and have a great day!

signatureSun Apr 16 2023
See all our articles