資料庫整合
新增將資料庫連線到Express應用程式的功能只需在應用程式中為資料庫載入適當的Node.js驅動程式,本文件簡要介紹瞭如何在Express應用程式中為資料庫系統新增和使用一些最流行的Node.js模組。
這些資料庫驅動程式是眾多可用的驅動程式,對於其他選項,請在npm網站上搜尋。
Cassandra
安裝
$ npm install cassandra-driver
示例
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])
})
Couchbase
模組:couchnode
安裝
$ npm install couchbase
示例
var couchbase = require(`couchbase`)
var bucket = (new couchbase.Cluster(`http://localhost:8091`)).openBucket(`bucketName`)
// add a document to a bucket
bucket.insert(`document-key`, { name: `Matt`, shoeSize: 13 }, function (err, result) {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
// get all documents with shoe size 13
var n1ql = `SELECT d.* FROM `bucketName` d WHERE shoeSize = $1`
var query = N1qlQuery.fromString(n1ql)
bucket.query(query, [13], function (err, result) {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
CouchDB
模組:nano
安裝
$ npm install nano
示例
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(err)
} else {
console.log(body)
}
})
// Get a list of all books
books.list(function (err, body) {
if (err) {
console.log(err)
} else {
console.log(body.rows)
}
})
LevelDB
模組:levelup
安裝
$ npm install level levelup leveldown
示例
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
模組:mysql
安裝
$ npm install mysql
示例
var mysql = require(`mysql`)
var connection = mysql.createConnection({
host : `localhost`,
user : `dbuser`,
password : `s3kreee7`,
database : `my_db`
});
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
模組:mongodb
安裝
$ npm install mongodb
示例(v2.*)
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)
})
})
示例(v3.*)
var MongoClient = require(`mongodb`).MongoClient
MongoClient.connect(`mongodb://localhost:27017/animals`, function (err, client) {
if (err) throw err
var db = client.db(`animals`)
db.collection(`mammals`).find().toArray(function (err, result) {
if (err) throw err
console.log(result)
})
})
如果你想要MongoDB的物件模型驅動程式,請檢視Mongoose。
Neo4j
模組:apoc
安裝
$ npm install apoc
示例
var apoc = require(`apoc`)
apoc.query(`match (n) return n`).exec().then(
function (response) {
console.log(response)
},
function (fail) {
console.log(fail)
}
)
Oracle
模組:oracledb
安裝
注意:請參閱安裝前提條件。
$ npm install oracledb
示例
const oracledb = require(`oracledb`);
const config = {
user: `<your db user>`, // Update me
password: `<your db password>`, // Update me
connectString: `localhost:1521/orcl` // Update me
};
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
安裝
$ npm install pg-promise
示例
var pgp = require(`pg-promise`)(/*options*/)
var db = pgp(`postgres://username:password@host:port/database`)
db.one(`SELECT $1 AS value`, 123)
.then(function (data) {
console.log(`DATA:`, data.value)
})
.catch(function (error) {
console.log(`ERROR:`, error)
})
Redis
模組:redis
安裝
$ npm install redis
示例
var redis = require(`redis`)
var client = 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()
})
SQL Server
模組:tedious
安裝
$ npm install tedious
示例
var Connection = require(`tedious`).Connection;
var Request = require(`tedious`).Request;
var config = {
userName: `your_username`, // update me
password: `your_password`, // update me
server: `localhost`
}
var connection = new Connection(config);
connection.on(`connect`, function(err) {
if (err) {
console.log(err);
} else {
executeStatement();
}
});
function executeStatement() {
request = new Request("select 123, `hello world`", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ` rows`);
}
connection.close();
});
request.on(`row`, function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log(`NULL`);
} else {
console.log(column.value);
}
});
});
connection.execSql(request);
}
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
安裝
$ 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)
})