Database integration

Adding the capability to connect databases to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app. This document briefly explains how to add and use some of the most popular Node.js modules for database systems in your Express app:

  • Cassandra
  • CouchDB
  • LevelDB
  • MySQL
  • MongoDB
  • Neo4j
  • PostgreSQL
  • Redis
  • SQLite
  • ElasticSearch

These database drivers are among many that are available. For other options, search on the npm site.

Cassandra

Module: cassandra-driver Installation

1
$ npm install cassandra-driver

Example

1
2
3
4
5
6
7
var cassandra = require('cassandra-driver');
var client = new cassandra.Client({ contactPoints: ['localhost']});
 
client.execute('select key from system.local', function(err, result) {
  if (err) throw err;
  console.log(result.rows[0]);
});

CouchDB

Module: nano Installation

1
$ npm install nano

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var nano = require('nano')('http://localhost:5984');
nano.db.create('books');
var books = nano.db.use('books');
 
//Insert a book document in the books database
books.insert({name: 'The Art of war'}, null, function(err, body) {
  if (!err){
    console.log(body);
  }
});
 
//Get a list of all books
books.list(function(err, body){
  console.log(body.rows);
});

LevelDB

Module: levelup Installation

1
$ npm install level levelup leveldown

Example

1
2
3
4
5
6
7
8
9
10
11
12
var levelup = require('levelup');
var db = levelup('./mydb');
 
db.put('name', 'LevelUP', function (err) {
 
  if (err) return console.log('Ooops!', err);
  db.get('name', function (err, value) {
    if (err) return console.log('Ooops!', err);
    console.log('name=' + value);
  });
 
});

MySQL

Module: mysql Installation

1
$ npm install mysql

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'dbuser',
  password : 's3kreee7'
});
 
connection.connect();
 
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  if (err) throw err;
  console.log('The solution is: ', rows[0].solution);
});
 
connection.end();

MongoDB

Module: mongodb Installation

1
$ npm install mongodb

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
var MongoClient = require('mongodb').MongoClient;
 
MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
  if (err) {
    throw err;
  }
  db.collection('mammals').find().toArray(function(err, result) {
    if (err) {
      throw err;
    }
    console.log(result);
  });
});

If you want an object model driver for MongoDB, look at Mongoose.

Neo4j

Module: apoc Installation

1
$ npm install apoc

Example

1
2
3
4
5
6
7
8
9
10
var apoc = require('apoc');
 
apoc.query('match (n) return n').exec().then(
  function (response) {
    console.log(response);
  },
  function (fail) {
    console.log(fail);
  }
);

PostgreSQL

Module: pg-promise Installation

1
$ npm install pg-promise

Example

1
2
3
4
5
6
7
8
9
10
var pgp = require("pg-promise")(/*options*/);
 
db.one("SELECT $1 AS value", 123)
    .then(function (data) {
        console.log("DATA:", data.value);
    })
    .catch(function (error) {
        console.log("ERROR:", error);
    });

Redis

Module: redis Installation

1
$ npm install redis

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var client = require('redis').createClient();
 
client.on('error', function (err) {
  console.log('Error ' + err);
});
 
client.set('string key', 'string val', redis.print);
client.hset('hash key', 'hashtest 1', 'some value', redis.print);
client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
 
client.hkeys('hash key', function (err, replies) {
 
  console.log(replies.length + ' replies:');
  replies.forEach(function (reply, i) {
    console.log('    ' + i + ': ' + reply);
  });
 
  client.quit();
 
});

SQLite

Module: sqlite3 Installation

1
$ npm install sqlite3

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
 
db.serialize(function() {
 
  db.run('CREATE TABLE lorem (info TEXT)');
  var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
 
  for (var i = 0; i < 10; i++) {
    stmt.run('Ipsum ' + i);
  }
 
  stmt.finalize();
 
  db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
    console.log(row.id + ': ' + row.info);
  });
});
 
db.close();

ElasticSearch

Module: elasticsearch Installation

1
$ npm install elasticsearch

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var elasticsearch = require('elasticsearch');
var client = elasticsearch.Client({
  host: 'localhost:9200'
});
 
client.search({
  index: 'books',
  type: 'book',
  body: {
    query: {
      multi_match: {
        query: 'express js',
        fields: ['title', 'description']
      }
    }
  }
}).then(function(response) {
  var hits = response.hits.hits;
}, function(error) {
  console.trace(error.message);
});
doc_Express
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.