2011-08-18 67 views
4

我正在寫一個簡單的測試應用程序來試驗node.js和couchdb的功能,到目前爲止我很喜歡它,但是我遇到了一個障礙。我尋找和廣泛,但似乎無法找到答案。我的測試服務器(一個簡單的地址簿)做兩件事情:使用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"); 

正如你所看到的,我需要填寫GetAllUsers()函數。任何幫助,將不勝感激。提前致謝。

回答

7

您可以創建一個CouchDB視圖來列出用戶。以下是CouchDB視圖幾種資源,您應該按順序閱讀來獲得有關這個主題的一個更大的圖片:

所以我們說你有這樣的文件結構:

{ 
    "_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視圖的基礎知識及其功能。

+0

感謝您的詳細回覆。 – Dewseph

+0

不回答這個問題。或幾乎對齊。 – ekerner

7

我希望你可以做這樣的事情(使用納米,這是我創作的一個庫):

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實現那邊卻是什麼感覺如果你正在尋找更多的例子,可以免費前往我的博客。只是wrote a blog post for people getting started with node and couch

如上所述,它會來一個時間,你將需要創建自己的看法。檢查CouchDB API Wiki,然後scan thru the book,檢查什麼是design documents,然後如果你喜歡,你可以去檢查test code I have for view generation and querying

+2

嗨!我在哪裏可以找到所有可以添加到例如列表功能的「參數」?也許我只是盲目的... – KungWaz