devnotes.

Update record in Cassandra using Express

Apache Cassandra is a distributed, highly available NoSQL database built for large datasets. Here's how to connect it to an Express app and update a record using express-cassandra.

Step 1: Run Cassandra in Docker

docker pull cassandra:latest
docker run -d --name cassandra-node -p 9042:9042 cassandra
docker exec -it cassandra-node bash
cqlsh

Create a keyspace to work in:

CREATE KEYSPACE shop_ks WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': 1 };
use shop_ks;

Step 2: Set up the Express project

mkdir cassandra-shop
cd cassandra-shop
npm init
npm install --save express
npm install express-cassandra

Step 3: Define a model

models/CustomerModel.js:

module.exports = {
    fields: {
        username: "text",
        city: "text",
        loyaltyPoints: "int",
        joined: "timestamp",
    },
    key: ["username"],
};

Step 4: Connect and configure

index.js:

const express = require("express");
const app = express();
const models = require("express-cassandra");

models.setDirectory(__dirname + "/models").bind(
    {
        clientOptions: {
            contactPoints: ["127.0.0.1"],
            protocolOptions: { port: 9042 },
            keyspace: "shop_ks",
            queryOptions: { consistency: models.consistencies.one },
        },
        ormOptions: {
            defaultReplicationStrategy: {
                class: "SimpleStrategy",
                replication_factor: 1,
            },
            migration: "safe",
        },
    },
    function (err) {
        if (err) throw err;
        app.listen(4000, () => console.log("Server running on port 4000"));
    }
);

Step 5: Create a record

app.get("/customer/:username/:city/:points", function (req, res) {
    res.send(
        `username: ${req.params.username}, city: ${req.params.city}, points: ${req.params.points}`
    );

    const customer = new models.instance.Customer({
        username: req.params.username,
        city: req.params.city,
        loyaltyPoints: parseInt(req.params.points),
        joined: Date.now(),
    });

    customer.save(function (err) {
        if (err) {
            console.log(err);
            return;
        }
        console.log("Customer saved!");
    });
});

Visiting http://localhost:4000/customer/nadia/Dhaka/120 inserts a matching row into shop_ks.customer.

Step 6: Update a record

app.put("/customer/:username/:city/:points?", function (req, res) {
    models.instance.Customer.findOne({ username: req.params.username }, function (err, customer) {
        if (err) throw err;

        if (customer) {
            if (req.params.city) {
                customer.city = req.params.city;
            }
            if (req.params.points) {
                customer.loyaltyPoints = parseInt(req.params.points);
            }
            customer.save(function (err) {
                if (err) console.log(err);
                else console.log("Customer record updated...");
            });
        }
    });

    res.send("Customer record updated");
});

Sending a PUT request to http://localhost:4000/customer/nadia/Chattogram/180 updates the city and loyaltyPoints fields for the nadia record.

Why express-cassandra

  • Lets you work with Cassandra using JavaScript objects and familiar model methods instead of raw CQL everywhere.
  • Automatically creates underlying tables from your model definitions.
  • Plays reasonably well with other Node frameworks thanks to its decoupled design.
Update record in Cassandra using Express | DevNotes