使用Node.js从couchdb检索所有文档

我正在编写一个简单的测试应用程序来试验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);
    });
});

这只是一个例子.首先,我建议您浏览上面的资源,了解CouchDB视图的基础知识及其功能.

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...