Illustration Image

Cassandra.Link

The best knowledge base on Apache Cassandra®

Helping platform leaders, architects, engineers, and operators build scalable real time data platforms.

10/23/2020

Reading time:2 min

DataStax-Examples/quickstart-nodejs

by DataStax-Examples

A basic demo CRUD application using the DataStax Node.js Driver for Apache Cassandra.Run the quickstart-complete.js file if you want to skip the exercise and run the application with the complete code.Contributors: Rebecca MillsProject Layoutquickstart.js - main application file with space to fill in CRUD operation codeusers.cql - Use this file to create the schemaObjectivesTo demonstrate how to perform basic CRUD operations with the DataStax Node.js Driver.The intent is to help users get up and running quickly with the driver.How this Sample WorksThis project walks through basic CRUD operations using Cassandra. The demo application will first insert a row of user data, select that same row back out, update the row and finally delete the user. The README includes the code snippets to be filled in to the main application code to complete the functionality.PrerequisitesA running instance of Apache Cassandra® 1.2+Node.js server environmentUse npm to install the driver: npm install cassandra-driverCreate the keyspace and tableThe users.cql file provides the schema used for this project:CREATE KEYSPACE demo WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};CREATE TABLE demo.users ( lastname text PRIMARY KEY, age int, city text, email text, firstname text);Connect to your clusterAll of our code is contained in the quickstart.js file.The cassandra.Client() instance connects to our cluster.You need to provide the address or host name of your node and your local data center name.// TO DO: Fill in your own host and data centerconst client = new cassandra.Client({ contactPoints: ['127.0.0.1'], localDataCenter: 'datacenter1', keyspace: 'demo' });CRUD OperationsFill the code in the functions that will add a user, get a user, update a user and delete a user from the table with the driver.INSERT a userfunction insertUser(lastname, age, city, email, firstname) { // TO DO: execute a prepared statement that inserts one user into the table const insert = 'INSERT INTO users (lastname, age, city, email, firstname) VALUES (?,?,?,?,?)'; const params = [ lastname, age, city, email, firstname ]; return client.execute(insert, params, { prepare : true });}SELECT a userfunction selectUser(lastname) { // TO DO: execute a prepared statement that retrieves one user from the table const select = 'SELECT firstname, age FROM users WHERE lastname = ?'; const params = [ lastname ] ; return client.execute(select, params, { prepare : true });}UPDATE a user's agefunction updateUser(age, lastname) { // TO DO: execute a prepared statement that updates the age of one user const update = 'UPDATE users SET age = ? WHERE lastname = ?'; return client.execute(update, [ age, lastname ], { prepare : true } )}DELETE a userfunction deleteUser(lastname) { // TO DO: execute a prepared that deletes one user from the table const remove = 'DELETE FROM users WHERE lastname = ?'; const params = [ lastname ]; return client.execute(remove, params, { prepare: true })}LicenseCopyright 2019 Rebecca MillsLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.

Illustration Image

A basic demo CRUD application using the DataStax Node.js Driver for Apache Cassandra. Run the quickstart-complete.js file if you want to skip the exercise and run the application with the complete code.

Contributors: Rebecca Mills

Project Layout

  • quickstart.js - main application file with space to fill in CRUD operation code
  • users.cql - Use this file to create the schema

Objectives

  • To demonstrate how to perform basic CRUD operations with the DataStax Node.js Driver.
  • The intent is to help users get up and running quickly with the driver.

How this Sample Works

This project walks through basic CRUD operations using Cassandra. The demo application will first insert a row of user data, select that same row back out, update the row and finally delete the user. The README includes the code snippets to be filled in to the main application code to complete the functionality.

Prerequisites

  • A running instance of Apache Cassandra® 1.2+
  • Node.js server environment
  • Use npm to install the driver: npm install cassandra-driver

Create the keyspace and table

The users.cql file provides the schema used for this project:

CREATE KEYSPACE demo
    WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};
CREATE TABLE demo.users (
    lastname text PRIMARY KEY,
    age int,
    city text,
    email text,
    firstname text);

Connect to your cluster

All of our code is contained in the quickstart.js file. The cassandra.Client() instance connects to our cluster. You need to provide the address or host name of your node and your local data center name.

// TO DO: Fill in your own host and data center
const client = new cassandra.Client({ 
  contactPoints: ['127.0.0.1'], 
  localDataCenter: 'datacenter1',  
  keyspace: 'demo' 
});

CRUD Operations

Fill the code in the functions that will add a user, get a user, update a user and delete a user from the table with the driver.

INSERT a user

function insertUser(lastname, age, city, email, firstname) {
  // TO DO: execute a prepared statement that inserts one user into the table
  const insert = 'INSERT INTO users (lastname, age, city, email, firstname) VALUES (?,?,?,?,?)';
  const params = [ lastname, age, city, email, firstname ];
  return client.execute(insert, params, { prepare : true });
}

SELECT a user

function selectUser(lastname) {
  // TO DO: execute a prepared statement that retrieves one user from the table
  const select = 'SELECT firstname, age FROM users WHERE lastname = ?';
  const params = [ lastname ] ;
  return client.execute(select, params, { prepare : true });
}

UPDATE a user's age

function updateUser(age, lastname) {
  // TO DO: execute a prepared statement that updates the age of one user
  const update = 'UPDATE users SET age = ? WHERE lastname = ?';
  return client.execute(update, [ age, lastname ], { prepare : true } )
}

DELETE a user

function deleteUser(lastname) {
  // TO DO: execute a prepared that deletes one user from the table
  const remove = 'DELETE FROM users WHERE lastname = ?';
  const params = [ lastname ];
  return client.execute(remove, params, { prepare: true })
}

License

Copyright 2019 Rebecca Mills

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Related Articles

api.management
node
api

LoopBack

John Doe

3/7/2024

Checkout Planet Cassandra

Claim Your Free Planet Cassandra Contributor T-shirt!

Make your contribution and score a FREE Planet Cassandra Contributor T-Shirt! 
We value our incredible Cassandra community, and we want to express our gratitude by sending an exclusive Planet Cassandra Contributor T-Shirt you can wear with pride.

Join Our Newsletter!

Sign up below to receive email updates and see what's going on with our company

Explore Related Topics

AllKafkaSparkScyllaSStableKubernetesApiGithubGraphQl

Explore Further

node