我正在编写一个简单的测试应用程序来试验node.js和couchdb的功能,到目前为止我很喜欢它,但我遇到了困难.我寻找和广泛,但似乎无法找到答案.我的测试服务器(一个简单的地址簿)做了两件事:
>如果用户转到localhost:8000 / {id},那么我的应用程序将返回具有该ID的用户的名称和地址.
>如果用户转到localhost:8000 /那么我的应用程序需要返回一个列表,这些名称是超链接并将它们带到localhost:8000 / {id}页面.
我能够得到第一个要求.我似乎无法找到如何从我的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()函数.任何帮助,将不胜感激.提前致谢.
解决方法
您可以创建一个列出用户的CouchDB视图.以下是有关CouchDB视图的几个资源,您应该阅读这些资源以便对此主题进行更全面的了解:
> Introduction to CouchDB Views
> Finding Your Data with Views
> View Cookbook for SQL Jockeys
> HTTP View API
所以,假设你有这样的文件:
{ "_id": generated by CouchDB,"_rev": generated by CouchDB,"type": "user","name": "Johny Bravo","isHyperlink": true }
然后你可以创建一个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); } } }
创建视图后,您可以从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); }); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。