数据库集成

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

这些数据库驱动程序是许多可用的驱动程序之一。如需其他选项,请在 npm 网站上搜索。

Cassandra

模块cassandra-driver

安装

$ npm install cassandra-driver

示例

const cassandra = require('cassandra-driver')
const client = new cassandra.Client({ contactPoints: ['localhost'] })

client.execute('select key from system.local', (err, result) => {
  if (err) throw err
  console.log(result.rows[0])
})

Couchbase

模块couchnode

安装

$ npm install couchbase

示例

const couchbase = require('couchbase')
const bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName')

// add a document to a bucket
bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
  if (err) {
    console.log(err)
  } else {
    console.log(result)
  }
})

// get all documents with shoe size 13
const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1'
const query = N1qlQuery.fromString(n1ql)
bucket.query(query, [13], (err, result) => {
  if (err) {
    console.log(err)
  } else {
    console.log(result)
  }
})

CouchDB

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw6LF4BDVJ3aFR9xuhdQ8yvyaA/T39BH8JFqEwNA+dzcdvOnVDw7iO77Retc2rD9bz0=

安装

$ npm install nano

示例

const nano = require('nano')('http://localhost:5984')
nano.db.create('books')
const books = nano.db.use('books')

// Insert a book document in the books database
books.insert({ name: 'The Art of war' }, null, (err, body) => {
  if (err) {
    console.log(err)
  } else {
    console.log(body)
  }
})

// Get a list of all books
books.list((err, body) => {
  if (err) {
    console.log(err)
  } else {
    console.log(body.rows)
  }
})

LevelDB

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw4w6suP4D9a8dYZtpPi67C3CxozXRlU5p1pvIkjqATVcIMWoiIq+mEpiPZpGGWoOJFDYJcdYaG87SOR/ZDbaIn0

安装

$ npm install level levelup leveldown

示例

const levelup = require('levelup')
const db = levelup('./mydb')

db.put('name', 'LevelUP', (err) => {
  if (err) return console.log('Ooops!', err)

  db.get('name', (err, value) => {
    if (err) return console.log('Ooops!', err)

    console.log(`name=${value}`)
  })
})

MySQL

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw5AU+Iw/qNAMmoAFY+5rL3kq0MkmQwGLLFUCiyPtKb5wvkqUsky13yrmG+jQ7f/aRZPrYMioAd9lxJyzDogfkys

安装

$ npm install mysql

示例

const mysql = require('mysql')
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'dbuser',
  password: 's3kreee7',
  database: 'my_db'
})

connection.connect()

connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
  if (err) throw err

  console.log('The solution is: ', rows[0].solution)
})

connection.end()

MongoDB

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw61+nhZ7yfexDeGTdMQQPS7/4vCA0iEqkeP3z4Yct//lOKKxSgAyoihS/fPlQtGBbxaBn06yI9RhW2ADBvqI1Dx

安装

$ npm install mongodb

示例 (v2.*)

const MongoClient = require('mongodb').MongoClient

MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
  if (err) throw err

  db.collection('mammals').find().toArray((err, result) => {
    if (err) throw err

    console.log(result)
  })
})

示例 (v3.*)

const MongoClient = require('mongodb').MongoClient

MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
  if (err) throw err

  const db = client.db('animals')

  db.collection('mammals').find().toArray((err, result) => {
    if (err) throw err

    console.log(result)
  })
})

1NJvuFdZE1+UN1kGSA9oOtXja4PVbqgvqB/eb7qLl4W6Otl1z/XLlmpYmZNBbBcheem7ZM9eN+3sr8mkg7eUQGCbAuVbMePp4jGQhpkCAfZywKZ6d+JgXQzwunCrUDQjot986CYmJsxvqJh5TeKAOolsOQfctusHEJ3y2eKFCPc=

Neo4j

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw6gmn3whPEtCgUfwixIYkVipYpZmnfBDK2FvQwuaoMU2M/qX84jB12hoZSQvW2QycSgKvO9CHZytd3kmZezeDqi

安装

$ npm install neo4j-driver

示例

const neo4j = require('neo4j-driver')
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'))

const session = driver.session()

session.readTransaction((tx) => {
  return tx.run('MATCH (n) RETURN count(n) AS count')
    .then((res) => {
      console.log(res.records[0].get('count'))
    })
    .catch((error) => {
      console.log(error)
    })
})

Oracle

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw6gWk9ym7b5U9i1+YuIv7aMj9HxqUxt8lcIlw7W9bFdkCA4V2reDCR9izWW0XinXc8T3xhWZjT3u3Smup/kaLde

安装

gtVqZ7SG3LCDh+z0QLZCmo8Wo89EFSVNC3VQeL5BQ84GTIO9jCwndc8YfEk0E7vkU+ZJDcIRn0rFhDtWeFZEnVAhGKnS4Fm1aPFUWZQ+jZ4O44DV33WNhLdfNiVHRdDq

$ npm install oracledb

示例

const oracledb = require('oracledb')
const config = {
  user: '<your db user>',
  password: '<your db password>',
  connectString: 'localhost:1521/orcl'
}

async function getEmployee (empId) {
  let conn

  try {
    conn = await oracledb.getConnection(config)

    const result = await conn.execute(
      'select * from employees where employee_id = :id',
      [empId]
    )

    console.log(result.rows[0])
  } catch (err) {
    console.log('Ouch!', err)
  } finally {
    if (conn) { // conn assignment worked, need to close
      await conn.close()
    }
  }
}

getEmployee(101)

PostgreSQL

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw5Htph8UUCzXIo3RKypOqqr2+OGqBEu5FIEKeKELbdZMHxoGg+P3JLo3oUsfBqLtIGZsvzCGKJKBkKHSpqsWzE8

安装

$ npm install pg-promise

示例

const pgp = require('pg-promise')(/* options */)
const db = pgp('postgres://username:password@host:port/database')

db.one('SELECT $1 AS value', 123)
  .then((data) => {
    console.log('DATA:', data.value)
  })
  .catch((error) => {
    console.log('ERROR:', error)
  })

Redis

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw6h3SKuM/cNia6f9FxSrtpxzKur/vfHS/s1m9SHL0EHHLUPx3ocHVgGVIhuYbfHbe1we2TJJuL7XecN5D/L7tFA

安装

$ npm install redis

示例

const redis = require('redis')
const client = redis.createClient()

client.on('error', (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', (err, replies) => {
  console.log(`${replies.length} replies:`)

  replies.forEach((reply, i) => {
    console.log(`    ${i}: ${reply}`)
  })

  client.quit()
})

SQL Server

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw7r86SQZW3xuij1fBLE2oL7iEipPcTrX+zx6j1jT6EnMqVuD7ioOHURiEwEwPhDGT19xY3kp5Y1frP6WGmucJ+9

安装

$ npm install tedious

示例

const Connection = require('tedious').Connection
const Request = require('tedious').Request

const config = {
  server: 'localhost',
  authentication: {
    type: 'default',
    options: {
      userName: 'your_username', // update me
      password: 'your_password' // update me
    }
  }
}

const connection = new Connection(config)

connection.on('connect', (err) => {
  if (err) {
    console.log(err)
  } else {
    executeStatement()
  }
})

function executeStatement () {
  request = new Request("select 123, 'hello world'", (err, rowCount) => {
    if (err) {
      console.log(err)
    } else {
      console.log(`${rowCount} rows`)
    }
    connection.close()
  })

  request.on('row', (columns) => {
    columns.forEach((column) => {
      if (column.value === null) {
        console.log('NULL')
      } else {
        console.log(column.value)
      }
    })
  })

  connection.execSql(request)
}

SQLite

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw4F5MPwTC+cHDuSczcZhFQRipB4dgqx0NWmD7287chP4dILLIlbPZQSQF3oojCTEdBtTlUxT5GnqxfzRD7OGHQI

安装

$ npm install sqlite3

示例

const sqlite3 = require('sqlite3').verbose()
const db = new sqlite3.Database(':memory:')

db.serialize(() => {
  db.run('CREATE TABLE lorem (info TEXT)')
  const stmt = db.prepare('INSERT INTO lorem VALUES (?)')

  for (let i = 0; i < 10; i++) {
    stmt.run(`Ipsum ${i}`)
  }

  stmt.finalize()

  db.each('SELECT rowid AS id, info FROM lorem', (err, row) => {
    console.log(`${row.id}: ${row.info}`)
  })
})

db.close()

Elasticsearch

BJm5vvy/Nz8W6qnJyiaD7L3A6ExiFe1cjX/u3SUeMw7f0k324nyyHV6Kqn2RLlmNiDY9iZw+xOpNAaM1phtPog8s3D3pmNWoMu/rhWATlQ3j0FmiaOYn8aLDB2kvUEZJ

安装

$ npm install elasticsearch

示例

const elasticsearch = require('elasticsearch')
const client = elasticsearch.Client({
  host: 'localhost:9200'
})

client.search({
  index: 'books',
  type: 'book',
  body: {
    query: {
      multi_match: {
        query: 'express js',
        fields: ['title', 'description']
      }
    }
  }
}).then((response) => {
  const hits = response.hits.hits
}, (error) => {
  console.trace(error.message)
})