How to update record in Cassandra using ExpressJS ?
Last Updated :
21 Mar, 2023
Apache Cassandra is a free and open-source, distributed, highly scalable, wide column store, NoSQL database management system. it is designed to handle large volumes of data, providing high availability with no single point of failure.
This article shows you that how to use Cassandra using express js and also shows how to update record in Cassandra using express Cassandra orm framework.
Features: The following features are used in this article.
- To configure Cassandra docker container using docker hub.
- To use express-cassandra orm framework for updating record in Cassandra using express js.
- CQLSH(Cassandra Query Language Shell) command(s).
Example: This example creates Person Table in Cassandra data store with the following columns/attributes.
JavaScript
module.exports = {
fields:{
name : "text",
surname : "text",
age : "int",
created : "timestamp"
},
key:["name"]
}
Then it inserts one record using expressjs restful endpoint using express-cassandra
cqlsh> select * from test_ks.person;
name | age | created | surname
------+-----+---------------------------------+---------
John | 32 | 2021-04-02 11:05:00.946000+0000 | Doe
Then it updates John(name column) record with surname Doe and age 55 with the help of express restful endpoint( please refer below Setting up Environment for updating record in Cassandra section further details).
cqlsh> select * from test_ks.person;
name | age | created | surname
------+-----+---------------------------------+---------
John | 55 | 2021-04-02 11:05:00.946000+0000 | Doe
(1 rows)
cqlsh>
Applications:
- Express-cassandra enables your nodejs app to manage a highly available distributed data store capable of handling a large dataset.
- Express-cassandra empowers you to manage and query from nodejs like you are just dealing with javascript objects and methods.
- Models are written as javascript modules and they automatically create the underlying DB tables. Then you can save, update, delete and query your data using the supported model method.
- Its decouple nature allows you to use it with many popular node frameworks without much hassle.
Setting up Environment for updating record in Cassandra: Please find the following steps to update record in Cassandra using express js.
Step 1: To setup Cassandra server in docker container.
Please use the following docker commands.
- docker pull cassandra:latest
- docker run -d --name cassandra-node -p 9042:9042 cassandra
- docker exec -it cassandra-node bash
- cqlsh
Note: prerequisite is to install docker hub for running cassandra server in docker container.
Please use the following cqlsh command(s) to create keyspace and create a tutorial table in Cassandra to walk through on how to update records in that express.js application for the next steps.
- CREATE KEYSPACE test_ks WITH replication = { 'class': 'SimpleStrategy', 'replication_factor':1};
- use test_ks;
Step 2: To setup express js application.
Please find the following command(s)
- mkdir mycassandratutorial
- cd mycassandratutorial
- npm init ( please feed all details like project name, author etc... )
- npm install --save express
- npm install express-cassandra
Note: prerequisite is to install node for running express js application.
Step 3: To setup cassandra connectivity using express-cassandra.
- Please find the following index.js file, where it has configured Cassandra Server IP Address and Port number and schema etc.
index.js
var express = require('express');
var app = express();
var models = require('express-cassandra');
// Tell express-cassandra to use the models-directory, and
// use bind() to load the models using cassandra configurations.
models.setDirectory( __dirname + '/models').bind(
{
clientOptions: {
contactPoints: ['127.0.0.1'],
protocolOptions: { port: 9042 },
keyspace: 'test_ks',
queryOptions: {consistency: models.consistencies.one}
},
ormOptions: {
defaultReplicationStrategy : {
class: 'SimpleStrategy',
replication_factor: 1
},
migration: 'safe'
}
},
function(err) {
if(err) throw err;
}
);
node index
Note:
- You'll now have a `person` table in cassandra created against the model schema defined in the above Step No.1. please refer the following output.
root@76561f8b27a2:/# cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.10 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
cqlsh> select * from test_ks.person;
name | age | created | surname
------+-----+---------+---------
(0 rows)
cqlsh>
- You can now access the model instance in `models.instance.Person` object containing supported orm operations.
- Please find the following PersonModel.js file under models folder.
PersonModel.js
module.exports = {
fields:{
name : "text",
surname : "text",
age : "int",
created : "timestamp"
},
key:["name"]
}
Note:Actually PersonModel.js maps into Cassandra table and does all the CRUD operation(s) using express-cassandra framework.
Step 4: To update record in Cassandra using express js restful API.
- To create a restful end point for creating new Person record into Cassandra.
index.js
// code snippet from the index.js file
app.get('/person/:name/:surname/:age', function(req, res) {
res.send('name: ' + req.params.name+', surname:'+req.params.surname+', age:'+req.params.age);
var person = new models.instance.Person({
name: req.params.name,
surname: req.params.surname,
age: parseInt(req.params.age),
created: Date.now()
});
person.save(function(err){
if(err) {
console.log(err);
return;
}
console.log('person saved!');
});
});
- You can access this end point  through web browser as http://localhost:3000/person/John/Doe/32 then you can get record created in Cassandra Person table.Â
root@76561f8b27a2:/# cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.10 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
cqlsh> select * from test_ks.person;
name | age | created | surname
------+-----+---------------------------------+---------
John | 32 | 2021-04-02 11:05:00.946000+0000 | Doe
(1 rows)
cqlsh>
- To update Person record from Cassandra through express js restful endpoint.
index.js
// code snippet from the index.js file
app.put('/person/:name/:surname/:age?', function (req, res) {
models.instance.Person.findOne({name: req.params.name }, function(err, person){
if(err) throw err;
if(person){
if(req.params.surname){
person.surname = req.params.surname;
}
if(req.params.age){
person.age = parseInt(req.params.age);
}
person.save(function(err){
if(err) console.log(err);
else console.log('Person got updated...');
});
}
});
res.send('person updated');
})
- You can access this end point through curl command as below.Â
Note: the below curl command update(s) John Doe age from 32 to 55.
MINGW64 ~
$ curl -v -X PUT http://localhost:3000/person/John/Doe/55 * Trying 127.0.0.1:3000...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3000 (#0)
> PUT /person/John/Doe/55 HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.67.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: text/html; charset=utf-8
< Content-Length: 14
< ETag: W/"e-TKKHGLrHAbIKlf0bIe4gdwzz0N0"
< Date: Fri, 02 Apr 2021 11:11:37 GMT
< Connection: keep-alive
<
person updated* Connection #0 to host localhost left intact
- Please find the following Cassandra Person table output.
root@76561f8b27a2:/# cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.10 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
cqlsh> select * from test_ks.person;
name | age | created | surname
------+-----+---------------------------------+---------
John | 55 | 2021-04-02 11:05:00.946000+0000 | Doe
(1 rows)
cqlsh>
Similar Reads
How to Update Data in JSON File using Node?
To update data in JSON file using Node.js, we can use the require module to directly import the JSON file. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and writing the updated data back to the file. Table of ContentUsing require() Me
4 min read
How to create routes using Express and Postman?
In this article we are going to implement different HTTP routes using Express JS and Postman. Server side routes are different endpoints of a application that are used to exchange data from client side to server side.Express.js is a framework that works on top of Node.js server to simplify its APIs
3 min read
How to Update value with put in Express/Node JS?
Express JS provides various HTTP methods to interact with data. Among these methods, the PUT method is commonly used to update existing resources. PrerequisitesNode JS Express JS In this article, we are going to setup the request endpoint on the server side using Express JS and Node JS. This endpoin
2 min read
How to update data in sqlite3 using Node.js ?
In this article, we are going to see how to update data in the sqlite3 database using node.js. So for this, we are going to use the run function which is available in sqlite3. This function will help us to run the queries for updating the data.SQLite is a self-contained, high-reliability, embedded,
4 min read
How to Build a RESTful API Using Node, Express, and MongoDB ?
This article guides developers through the process of creating a RESTful API using Node.js, Express.js, and MongoDB. It covers setting up the environment, defining routes, implementing CRUD operations, and integrating with MongoDB for data storage, providing a comprehensive introduction to building
6 min read
REST API CRUD Operations Using ExpressJS
In modern web development, REST APIs enable seamless communication between different applications. Whether itâs a web app fetching user data or a mobile app updating profile information, REST APIs provide these interactions using standard HTTP methods. What is a REST API?A REST API (Representational
7 min read
How To Update An "array of objects" With Firestore?
Firestore, a NoSQL database from Firebase, is widely used for building real-time, scalable web and mobile applications. One of the common tasks while working with Firestore is updating documents, particularly when working with complex data structures like arrays of objects.In this article, we will w
6 min read
Task Management System using Node and Express.js
Task Management System is one of the most important tools when you want to organize your tasks. NodeJS and ExpressJS are used in this article to create a REST API for performing all CRUD operations on task. It has two models User and Task. ReactJS and Tailwind CSS are used to create a frontend inter
15+ min read
How to update single and multiple documents in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
2 min read
How to insert request body into a MySQL database using Express js
If you trying to make an API with MySQL and Express JS to insert some data into the database, your search comes to an end. In this article, you are going to explore - how you can insert the request data into MySQL database with a simple Express JS app.Table of Content What is Express JS?What is MySQ
3 min read