添加将数据库连接到Express应用程序的功能仅是为应用程序中的数据库加载适当的Node.js驱动程序。本文档简要说明了如何在Express应用程序中为数据库系统添加和使用一些最受欢迎的Node.js模块:

Cassandra

模块: cassandra-driver

安装

  1. $ npm install cassandra-driver

示例

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

Couchbase

模块: couchnode

安装

  1. $ npm install couchbase

示例

  1. var couchbase = require('couchbase')
  2. var bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName')
  3. // add a document to a bucket
  4. bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, result) {
  5. if (err) {
  6. console.log(err)
  7. } else {
  8. console.log(result)
  9. }
  10. })
  11. // get all documents with shoe size 13
  12. var n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1'
  13. var query = N1qlQuery.fromString(n1ql)
  14. bucket.query(query, [13], function (err, result) {
  15. if (err) {
  16. console.log(err)
  17. } else {
  18. console.log(result)
  19. }
  20. })

CouchDB

模块: nano

安装

  1. $ npm install nano

示例

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

LevelDB

模块: levelup

安装

  1. $ npm install level levelup leveldown

示例

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

MySQL

模块: mysql

安装

  1. $ npm install mysql

示例

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

MongoDB

模块: mongodb

安装

  1. $ npm install mongodb

示例(v2.*)

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

示例(v3.*)

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

如果要使用MongoDB的对象模型驱动程序,请查看Mongoose

Neo4j

模块: apoc

安装

  1. $ npm install apoc

示例

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

Oracle

模块: oracledb

安装

注意:请参阅安装先决条件

  1. $ npm install oracledb

示例

  1. const oracledb = require('oracledb')
  2. const config = {
  3. user: '<your db user>',
  4. password: '<your db password>',
  5. connectString: 'localhost:1521/orcl'
  6. }
  7. async function getEmployee (empId) {
  8. let conn
  9. try {
  10. conn = await oracledb.getConnection(config)
  11. const result = await conn.execute(
  12. 'select * from employees where employee_id = :id',
  13. [empId]
  14. )
  15. console.log(result.rows[0])
  16. } catch (err) {
  17. console.log('Ouch!', err)
  18. } finally {
  19. if (conn) { // conn assignment worked, need to close
  20. await conn.close()
  21. }
  22. }
  23. }
  24. getEmployee(101)

PostgreSQL

模块: pg-promise

安装

  1. $ npm install pg-promise

示例

  1. var pgp = require('pg-promise')(/* options */)
  2. var db = pgp('postgres://username:password@host:port/database')
  3. db.one('SELECT $1 AS value', 123)
  4. .then(function (data) {
  5. console.log('DATA:', data.value)
  6. })
  7. .catch(function (error) {
  8. console.log('ERROR:', error)
  9. })

Redis

模块: redis

安装

  1. $ npm install redis

示例

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

SQL Server

模块: tedious

安装

  1. $ npm install tedious

示例

  1. var Connection = require('tedious').Connection
  2. var Request = require('tedious').Request
  3. var config = {
  4. userName: 'your_username', // update me
  5. password: 'your_password', // update me
  6. server: 'localhost'
  7. }
  8. var connection = new Connection(config)
  9. connection.on('connect', function (err) {
  10. if (err) {
  11. console.log(err)
  12. } else {
  13. executeStatement()
  14. }
  15. })
  16. function executeStatement () {
  17. request = new Request("select 123, 'hello world'", function (err, rowCount) {
  18. if (err) {
  19. console.log(err)
  20. } else {
  21. console.log(rowCount + ' rows')
  22. }
  23. connection.close()
  24. })
  25. request.on('row', function (columns) {
  26. columns.forEach(function (column) {
  27. if (column.value === null) {
  28. console.log('NULL')
  29. } else {
  30. console.log(column.value)
  31. }
  32. })
  33. })
  34. connection.execSql(request)
  35. }

SQLite

模块: sqlite3

安装

$ npm install sqlite3

示例

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

模块: elasticsearch

安装

$ npm install elasticsearch

示例

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)
})