2012-02-16 29 views
1

我想用nano來編寫一個帶有可重用數據庫調用的小型庫。CouchDB和nano.js的回調和返回

db.view('list', 'people', function(error, data) { 
    if (error == null) { 
    res.render('people/index', { 
     people: data.rows 
    }); 
    } else { 
    // error 
    } 
}); 

有多個請求時,可以得到相當混亂:

db.view('list', 'people', function(error, people) { 
    db.view('list', 'items', function(error, items) { 
    db.view('list', 'questions', function(error, questions) { 
     db.view('list', 'answers', function(error, answers) { 
     ... 
     res.render('people/index', { 
      people: people.rows, 
      items: items.rows, 
      questions: questions.rows 
      ... 

所以,當時的想法是創建一個函數:

var getPeople = function() { 
    // do db calls here and return 
} 

res.render('people/index', { 
    people: getPeople() 
}); 

但是,這並不工作。

我該如何解決這個問題,並將所有內容放入外部節點-js-module.js文件中?

回答

1

你得到了一些偉大的答案在這裏了。

從納米源代碼,你有一個例子,可以幫助:

此外,如果你真的不明白如何流動的NodeJS控制作品我不能推薦足夠你看到這個教程:

比使用工具更好的是使用工具瞭解它是如何工作的:)也許你最終會編寫自己的控制流程,這就是我們大多數人最終做的事情。

希望這有助於附加代碼,以方便。

var db = require('nano')('http://localhost:5984/emails') 
    , async = require('async') 
    ; 

    function update_row(row,cb) { 
    var doc = row.doc; 
    delete doc.subject; 
    db.insert(doc, doc._id, function (err, data) { 
     if(err) { console.log('err at ' + doc._id); cb(err); } 
     else  { console.log('updated ' + doc._id); cb(); } 
    }); 
    } 

    function list(offset) { 
    var ended = false; 
    offset = offset || 0; 
    db.list({include_docs: true, limit: 10, skip: offset}, 
     function(err, data) { 
     var total, offset, rows; 
     if(err) { console.log('fuuuu: ' + err.message); rows = []; return; } 
     total = data.total_rows; 
     offset = data.offset; 
     rows = data.rows; 
     if(offset === total) { 
      ended = true; 
      return; 
     } 
     async.forEach(rows, update_row, function (err) { 
      if(err) { console.log('something failed, check logs'); } 
      if(ended) { return; } 
      list(offset+10); 
     }); 
    }); 
    } 

    list(); 
+0

答案中的視頻鏈接已關閉,在此處找到副本:http://vimeo.com/19519289 – 2013-12-07 10:40:21

2

您是否考慮過在CouchDB中查看您的視圖的排序規則?這將幫助您減少db.view(..)調用的次數並返回1視圖查詢中需要的所有數據。單個一對多(即'人'有許多'項目')很容易。這可能是多層次的更多努力,但它應該以同樣的方式工作。這裏對於沙發觀點整理了一些好文章:

CouchDB Joins

CouchDB View Collation