couchDB是一個非常易用的nosql資料庫,到官網下載安裝並啟動它,然後建立一JS檔案:
var http = require('http');var options = { port: 5984, method: 'GET', // path:"/_all_dbs"};//這個回調果真只有一個參數,即http.createServer(function(req, res) {})var req = http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); var body = "" res.on('data', function (chunk) { body += chunk }); res.once("end", function(){ var json = JSON.parse(body); console.log(json) })});req.end()req.on('error', function(e) { console.log('problem with request: ' + e.message);});
然後用node.js開啟它!控制台輸出如下訊息,表示成功:
STATUS: 200HEADERS: {"server":"CouchDB/1.2.0 (Erlang OTP/R14B04)","date":"Fri, 24 Aug 201202:53:18 GMT","content-type":"text/plain; charset=utf-8","content-length":"40","cache-control":"must-revalidate"}{ couchdb: 'Welcome', version: '1.2.0' }
然後我們修改一下上面的options對象,查看裡面已經有多少個資料庫
var options = { port: 5984, method: 'GET', path:"/_all_dbs"};
會輸出一個數組
[ '_replicator', '_users' ]
建立一個資料庫,為PUT請求,path為資料庫名
var options = { port: 5984, method: 'PUT', path:"/aaa"};
輸出ok=true表示成功
{ ok: true }
注,不能重複建立相同資料庫,我們試再發一次上面的請求,會返回上面請求
{ error: 'file_exists', reason: 'The database could not be created, the file already exists.' }
刪除一個資料庫就用DELETE請求,path為資料庫名
var options = { port: 5984, method: 'DELETE', path:"/aaa"};
在一個資料庫插入入一條記錄,因為上面的aaa被我們刪掉了, 我們就再搞個albums
var options = { port: 5984, method: 'PUT', path:"/albums"};
插入新記錄,記錄在nosql資料庫大多數稱之為文檔.它要求有一個UUID,你就隨便造一個吧
var http = require('http');//建立一個名為baseball的資料庫var options = { port: 5984, method: 'PUT', path:"/albums/1"};var req = http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); var body = "" res.on('data', function (chunk) { body += chunk }); res.once("end", function(){ var json = JSON.parse(body); console.log(json) })});req.setHeader("Content-Type", "application/json")//這時請補上文檔內容req.write(JSON.stringify({ "title":"There is Nothing Left to Lose", "artist":"Foo Fighters"}))req.end()req.on('error', function(e) { console.log('problem with request: ' + e.message);});
當然,上面這樣搞出來的UUID太不安全了,因此你可以利用couthDB給你的UUID
var options = { port: 5984, method: 'GET', path:"/_uuids"};
我們再把剛才儲存的文檔取出來吧,就是資料庫加ID名,GET請求
var options = { port: 5984, method: 'GET', path:"/albums/1"};