使用Node.js检索来自couchdb的所有文档

我正在写一个简单的testing应用程序来实验node.js和couchdb的function,到目前为止我很喜欢它,但是我遇到了麻烦。 我已经find和广泛,但似乎无法find答案。 我的testing服务器(一个简单的地址簿)有两件事情:

  1. 如果用户转到localhost:8000/{id}那么我的应用程序返回该用户的名称和地址与该ID。
  2. 如果用户转到localhost:8000/那么我的应用程序需要返回一个列表超链接的名称,并把它们带到页面localhost:8000/{id}

我能够得到第一个要求的工作。 我似乎无法find如何从我的couchdb检索所有名称的列表。 这是我需要帮助。 这里是我的代码:

 var http = require('http'); var cradle = require('cradle'); var conn = new(cradle.Connection)(); var db = conn.database('users'); function getUserByID(id) { var rv = ""; db.get(id, function(err,doc) { rv = doc.name; rv += " lives at " + doc.Address; }); return rv; } function GetAllUsers() { var rv = "" return rv; } var server = http.createServer(function(req,res) { res.writeHead(200, {'Content-Type':'text/plain'}); var rv = "" ; var id = req.url.substr(1); if (id != "") rv = getUserByID(id); else rv = GetAllUsers(); res.end(rv); }); server.listen(8000); console.log("server is runnig"); 

正如你所看到的,我需要填写GetAllUsers()函数。 任何帮助,将不胜感激。 提前致谢。

你可以创build一个CouchDB视图来列出用户。 以下是关于CouchDB视图的几个资源,您应该阅读这些资源,以便更好地了解此主题:

  • CouchDB视图简介
  • 使用视图查找数据
  • 查看SQL骑师的食谱
  • HTTP视图API

假设你有这样的文件结构:

 { "_id": generated by CouchDB, "_rev": generated by CouchDB, "type": "user", "name": "Johny Bravo", "isHyperlink": true } 

然后你可以创build一个CouchDB视图(地图部分),看起来像这样:

 // view map function definition function(doc) { // first check if the doc has type and isHyperlink fields if(doc.type && doc.isHyperlink) { // now check if the type is user and isHyperlink is true (this can also inclided in the statement above) if((doc.type === "user") && (doc.isHyperlink === true)) { // if the above statements are correct then emit name as it's key and document as value (you can change what is emitted to whatever you want, this is just for example) emit(doc.name, doc); } } } 

当创build视图时,您可以从您的node.js应用程序中查询它:

 // query a view db.view('location of your view', function (err, res) { // loop through each row returned by the view res.forEach(function (row) { // print out to console it's name and isHyperlink flag console.log(row.name + " - " + row.isHyperlink); }); }); 

这只是一个例子。 首先,我会build议通过上面的资源,了解CouchDB视图的基础知识和function。

我希望你能做些像(使用nano,这是我创作的库):

 var db = require('nano')('http://localhost:5984/my_db') , per_page = 10 , params = {include_docs: true, limit: per_page, descending: true} ; db.list(params, function(error,body,headers) { console.log(body); }); 

我不是很确定你想用http来完成什么,但如果你正在寻找更多的例子,请随时前往我的博客。 刚刚写了一个博客文章,让人们开始使用节点和沙发

如上所述,您将需要创build自己的观点。 检查CouchDB API Wiki ,然后扫描本书 ,检查什么是devise文档 ,如果你喜欢,可以去检查我的视图生成和查询的testing代码 。