Retrieving all Documents from couchdb using Node.js

Dewseph picture Dewseph · Aug 18, 2011 · Viewed 11.2k times · Source

I am writing a simple test app to experiment with the functionality of node.js and couchdb, so far i am loving it, but i ran in a snag. i have looked for and wide but can't seem to find an answer. My test server(a simple address book) does 2 things:

  1. if the user goes to localhost:8000/{id} then my app returns the name and address of the user with that id.
  2. if the user goes to localhost:8000/ then my app needs to return a list a names that are hyperlinks and takes them to the page localhost:8000/{id}.

I was able to get the first requirement working. i cant not seem to find how to retrieve a list of all names from my couchdb. that is what i need help with. here is my code:

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

As you can see, I need to fill in the GetAllUsers() function. Any help would be appreciated. Thanks in advance.

Answer

dscape picture dscape · Sep 5, 2011

I would expect you to be doing something like (using nano, which is a library I authored):

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

I'm not pretty sure what you are trying to accomplish with http over there but feel free to head to my blog if you are looking for some more examples. Just wrote a blog post for people getting started with node and couch

As said above it will come a time when you will need to create your own view. Check up the CouchDB API Wiki, then scan thru the book, check what are design documents, then if you like you can go and check the test code I have for view generation and querying.