2012-02-16 69 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