数据库集成

要将数据库连接到 Express 应用程序,只需在该应用程序中为数据库装入相应的 Node.js 驱动程序。本文档简要说明如何在 Express 应用程序中为数据库系统添加和使用某些最流行的 Node.js 模块:

这些数据库驱动程序是众多可用数据库驱动程序的一部分。要了解其他选项,请在 npm 站点上搜索。

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

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(body);
  8. }
  9. });
  10. //Get a list of all books
  11. books.list(function(err, body){
  12. console.log(body.rows);
  13. }

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. });
  7. connection.connect();
  8. connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  9. if (err) throw err;
  10. console.log('The solution is: ', rows[0].solution);
  11. });
  12. connection.end();

MongoDB

模块mongodb 安装

  1. $ npm install mongodb

示例

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

如果您需要 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. );

PostgreSQL

模块pg 安装

  1. $ npm install pg

示例

  1. var pg = require('pg');
  2. var conString = "postgres://username:password@localhost/database";
  3. pg.connect(conString, function(err, client, done) {
  4. if (err) {
  5. return console.error('error fetching client from pool', err);
  6. }
  7. client.query('SELECT $1::int AS number', ['1'], function(err, result) {
  8. done();
  9. if (err) {
  10. return console.error('error running query', err);
  11. }
  12. console.log(result.rows[0].number);
  13. });
  14. });

Redis

模块redis 安装

  1. $ npm install redis

示例

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

SQLite

模块sqlite3 安装

  1. $ npm install sqlite3

示例

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

ElasticSearch

模块elasticsearch 安装

  1. $ npm install elasticsearch

示例

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