数据库集成
将连接数据库的功能添加到 Express 应用中,只需在应用中加载适合的数据库 Node.js 驱动程序即可。本文档简要说明了如何在 Express 应用中添加和使用一些最受欢迎的用于数据库系统的 Node.js 模块:
🌐 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:
- 卡桑德拉
- Couchbase
- CouchDB
- LevelDB
- MySQL
- MongoDB
- Neo4j
- 甲骨文
- PostgreSQL
- Redis
- SQL Server
- SQLite
- Elasticsearch
Caution
卡桑德拉
🌐 Cassandra
模块: cassandra-driver
安装
🌐 Installation
npm install cassandra-driveryarn add cassandra-driverpnpm add cassandra-driverbun add cassandra-driver示例
🌐 Example
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]);});import cassandra from '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
安装
🌐 Installation
npm install couchbaseyarn add couchbasepnpm add couchbasebun add couchbase示例
🌐 Example
const couchbase = require('couchbase');const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
// add a document to a bucketbucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => { if (err) { console.log(err); } else { console.log(result); }});
// get all documents with shoe size 13const 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); }});import couchbase from 'couchbase';
const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
// add a document to a bucketbucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => { if (err) { console.log(err); } else { console.log(result); }});
// get all documents with shoe size 13const 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
模块: nano
安装
🌐 Installation
npm install nanoyarn add nanopnpm add nanobun add nano示例
🌐 Example
const nano = require('nano')('http://localhost:5984');nano.db.create('books');const books = nano.db.use('books');
// Insert a book document in the books databasebooks.insert({ name: 'The Art of war' }, null, (err, body) => { if (err) { console.log(err); } else { console.log(body); }});
// Get a list of all booksbooks.list((err, body) => { if (err) { console.log(err); } else { console.log(body.rows); }});LevelDB
模块: levelup
安装
🌐 Installation
npm install level levelup leveldownyarn add level levelup leveldownpnpm add level levelup leveldownbun add level levelup leveldown示例
🌐 Example
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}`); });});import levelup from '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
模块: mysql
安装
🌐 Installation
npm install mysqlyarn add mysqlpnpm add mysqlbun add mysql示例
🌐 Example
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();import mysql from '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
模块: mongodb
安装
🌐 Installation
npm install mongodbyarn add mongodbpnpm add mongodbbun add mongodb示例 (v2.*)
🌐 Example (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.*)
🌐 Example (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); });});如果你想要一个用于 MongoDB 的对象模型驱动,可以看看 Mongoose。
🌐 If you want an object model driver for MongoDB, look at Mongoose.
Neo4j
模块: neo4j-driver
安装
🌐 Installation
npm install neo4j-driveryarn add neo4j-driverpnpm add neo4j-driverbun add neo4j-driver示例
🌐 Example
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); });});import neo4j from '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
模块: oracledb
安装
🌐 Installation
注意:查看安装前提条件。
🌐 NOTE: See installation prerequisites.
npm install oracledbyarn add oracledbpnpm add oracledbbun add oracledb示例
🌐 Example
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);import oracledb from '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
模块: pg-promise
安装
🌐 Installation
npm install pg-promiseyarn add pg-promisepnpm add pg-promisebun add pg-promise示例
🌐 Example
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
模块: redis
安装
🌐 Installation
npm install redisyarn add redispnpm add redisbun add redis示例
🌐 Example
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();});import redis from '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 服务器
🌐 SQL Server
模块: tedious
安装
🌐 Installation
npm install tediousyarn add tediouspnpm add tediousbun add tedious示例
🌐 Example
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
模块: sqlite3
安装
🌐 Installation
npm install sqlite3yarn add sqlite3pnpm add sqlite3bun add sqlite3示例
🌐 Example
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
模块: elasticsearch
安装
🌐 Installation
npm install elasticsearchyarn add elasticsearchpnpm add elasticsearchbun add elasticsearch示例
🌐 Example
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); } );import elasticsearch from '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); } );