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

Dew*_*eph 4 couchdb node.js cradle

我正在编写一个简单的测试应用程序来试验node.js和couchdb的功能,到目前为止我很喜欢它,但我遇到了困难.我寻找和广泛,但似乎无法找到答案.我的测试服务器(一个简单的地址簿)做了两件事:

  1. 如果用户转到localhost:8000/{id}那时我的应用程序返回具有该ID的用户的名称和地址.
  2. 如果用户转到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");
Run Code Online (Sandbox Code Playgroud)

如您所见,我需要填写GetAllUsers()函数.任何帮助,将不胜感激.提前致谢.

yoj*_*o87 8

您可以创建一个列出用户的CouchDB视图.以下是有关CouchDB视图的几个资源,您应该阅读这些资源以便对此主题进行更全面的了解:

所以,假设你有这样的文件:

{
    "_id": generated by CouchDB,
    "_rev": generated by CouchDB,
    "type": "user",
    "name": "Johny Bravo",
    "isHyperlink": true
}
Run Code Online (Sandbox Code Playgroud)

然后你可以创建一个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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

创建视图后,您可以从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);
    });
});
Run Code Online (Sandbox Code Playgroud)

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


dsc*_*ape 7

我希望你做的事情(使用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);
});
Run Code Online (Sandbox Code Playgroud)

我不太确定你想要http在那里完成什么,但如果你正在寻找更多的例子,请随时前往我的博客.刚刚为人们开始使用节点和沙发写了一篇博文

如上所述,您将需要创建自己的视图.检查CouchDB API Wiki,然后通过本书扫描,查看什么是设计文档,然后如果您愿意,可以查看我用于查看生成和查询测试代码.

  • 嗨!我在哪里可以找到你可以添加的所有"参数",例如列表功能?也许我只是盲目...... (2认同)