Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Wed Oct 04 2023

Delete a single entity in Datastore

I currently did some work on a hobby project where I was using Datastore. I came into a situation where I wanted to delete one single entity by its ID, and I had some trouble and couldn't really find any good documentation on it. Most of the guides I could find was how to delete the whole kind in the namespace or similar. So, if you are looking for the same issue, I hope this short guide could give you some guidance.

In this guide we will demonstrate how to delete an entity in GCP Datastore by its id. We will use NodeJs. If you are looking for how to add and retrieve data from Datastore, you can access it on our guide to add and get data from Datastore.

Prerequisites

As stated, we will use NodeJs for this. So go ahead and install it if you haven't. We will also use Datastore from @google-cloud/datastore. You can download it from npm with:

npm i @google-cloud/datastore

Solution

So, in this example, we will have multiple entities in our Datastore as below image is demonstrating

datastore

and then we will create a function that will delete a single entity from the Datastore using its id. Our function will take in the kind and the value of the id that we want to delete as arguments.

const deleteEntityById = async (kind, value) => { const key = datastore.key([kind]); key.id = value; await datastore.delete(key); return null; };

And then we can simply call it like:

await deleteEntityById("employees", "6218954821337088");

And now, the entity with id 6218954821337088 is successfully deleted.

Summary

This was a very quick guide on how to remove a single entity from the Datastore using NodeJs and Google Datastore. I hope you found this article useful, and thanks for reading.

Have a great day,

signatureWed Oct 04 2023
See all our articles