couchDB学习笔记

2012-08-25 06:28

couchDB学习笔记

by 司徒正美

at 2012-08-24 22:28:00

original http://www.cnblogs.com/rubylouvre/archive/2012/08/24/2653863.html

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"};

本文链接