Javascript 使用jade、express和monk渲染所有数据的视图

Javascript 使用jade、express和monk渲染所有数据的视图,javascript,node.js,mongodb,express,pug,Javascript,Node.js,Mongodb,Express,Pug,Mymongodb数据库有两个集合notes,分别保存每个笔记和note笔记本,其中包含一个标题和notes数组,其中ids指向notes集合中的笔记 //notes: { "_id" : ObjectId("542afaaa4898f4042312872b"), "title" : "Hello Universe", "content" : "Saving to

My
mongodb
数据库有两个集合
notes
,分别保存每个笔记和
note
笔记本,其中包含一个标题和
notes
数组,其中
id
s指向
notes
集合中的
笔记

//notes:
{
    "_id" : ObjectId("542afaaa4898f4042312872b"),
    "title" : "Hello Universe",
    "content" : "Saving to database"
}

//notebook
{
    "_id" : ObjectId("53d0c6d8daeac43cf8412945"),
    "title" : "My Notebook",
    "notes" : [
            ObjectId("53d0ca2fdaeac43cf8412946"),
            ObjectId("542afe34a25e3c44160e6b05"),
            ObjectId("542b7908a459766020342eae"),
            ObjectId("542b79efa459766020342eaf"),
            ObjectId("542b7a5ba459766020342eb0"),
            ObjectId("542b7aa3d3b135c022b674ff"),
            ObjectId("542bb47aa4ff29c820c22fdc"),
            ObjectId("542bb720a4ff29c820c22fdd"),
            ObjectId("542bddd5712c0dc426d41341"),
            ObjectId("542bdec5712c0dc426d41342")
    ]
}
我使用这些来检索数据。这是我的
路线的代码:

   router.get('/main',function(req,res){
var db=req.db;
var notebookCollection=db.get('notebook');
var notesCollection=db.get('notes');
var locals={};
locals.title="TakeNote:An easy to use note taking app for web and hopefully mobile";
locals.sidebar={};
locals.sidebar.items=[];
//get data for the first notebook and display it by default
locals.notebook={};
locals.notebook.notes=[];
notebookCollection.find({},{},function(err,docs){
    if(err)
        console.error(err);
    else
    {
        console.log("Retrieving notebooks");
        var noteIds;
        if(docs.length)
        {
            console.log(docs)
            for(var i=0;i<docs.length;i++)
            {
                locals.sidebar.items.push(docs[i].title);
                locals.notebook.title=docs[i].title;
                noteIds=docs[i].notes;
                for(var j=0;j<noteIds.length;j++)
                {
                    notesCollection.findOne({_id:noteIds[j]},function(err,doc){
                        if(err)
                            console.error(err);
                        else
                        {
                            locals.notebook.notes.push(doc);
                            //res.render('main',locals);
                        }   
                    });
                    //putting it here might mean that it renders without any of the notes
                    //putting it here with a condition fails
                    /*
                    if(j===noteIds.length-1)
                        res.render('main',locals);
                    */
                }   
            }
            //putting it here means it renders without any of the notes 
        }   
    }   
});
这是我的异步代码:

  function getActiveNotes(doc)
{
    var noteIds=doc.notes;
    async.map(noteIds,function(_id){
        notesCollection.findOne({_id:_id})
    },function(err,docs){
        if(err)
            console.error(err);
        else
        {
            if(docs)
                locals.notebook.notes=docs;
        }   
    });
}

function getAllNotebooks()
{
    notebookCollection.find({},{},function(err,docs){
        if(err)
            console.error(err);
        else
        {
            if(docs)
            {
                for(var i=0;i<docs.length;i++)
                {
                    locals.sidebar.items.push(docs[i].title);   
                }   
            }   
        }   
    });
}

function activeNotesOp(){
    async.waterfall([notebookCollection.findOne({isActive:true}),getActiveNotes]);  
}
async.parallel([getAllNotebooks,activeNotesOp],function(err,results){
    if(err)
        console.error(err);
    else
        console.log(results);
});
函数getActiveNotes(doc) { var noteIds=doc.notes; map(noteIds,function(\u id){ notesCollection.findOne({u-id:{u-id}) },函数(错误,文档){ 如果(错误) 控制台错误(err); 其他的 { 如果(文档) locals.notebook.notes=docs; } }); } 函数getAllNotebook() { 查找({},{},函数(err,docs){ 如果(错误) 控制台错误(err); 其他的 { 如果(文档) {
for(var i=0;iOn reflection
parallel
可能不是您需要的,但我认为这是一个有用的框架

var notebooksIdx = 0;

notebookCollection.find({},{},function(err,notebooks){

    async.each(
        notebooks,
    ,   function(notebook, cb) {

            notesCollection.find({_id: {$in: notebook.notes}}, function(err, notes) {

                if (err) 
                    return cb(err);

                return locals.notebook[notebooksIdx++].notes = notes;
            })
        }
    ,   function(err) {
            if (err) throw err;

            res.render(....)
        }
    });

});

我使用
lodash
方法
forEach
获取每个
笔记本的标题
来填充
局部变量。侧栏
,我使用
lodash.filter
(这将返回一个数组,从第一项获得)要查找
activeNotebook
并使用
$in
操作符从中检索所有笔记,请对笔记本中包含的所有笔记执行查询,并使用该数据填充
locals.notebook.notes

 notebookCollection.find({},{},function(err,notebooks){
    if(err)
        console.error(err);
    else
    {
        _(notebooks).forEach(function(notebook){
            locals.sidebar.items.push(notebook.title);
        });
        //console.log(locals.sidebar.items);
        var activeNotebooks= _.filter(notebooks,function(notebook){
            return notebook.isActive;
        });
        var notes=activeNotebooks[0].notes;
        notesCollection.find({_id:{$in:notes}},function(err,docs){
            if(err)
                console.error(err);
            else
            {
                if(docs.length)
                {
                    locals.notebook.notes=docs;
                    console.dir(locals);
                    res.render('main',locals);
                }   
            }   
        });
    }       
});

我建议您使用两个嵌套的async.parallel命令(一个用于获取笔记本;一个用于获取笔记)当外部循环完成@SimonH时运行渲染函数我添加了
async
库,我在这里试图做的是拥有多个笔记本,将其中一个笔记本标记为活动笔记本并检索该笔记本的数据。我使用
瀑布
检索活动笔记本及其笔记,并并行检索所有笔记本笔记本标题。但我得到了这个错误,我已经添加到问题中
 notebookCollection.find({},{},function(err,notebooks){
    if(err)
        console.error(err);
    else
    {
        _(notebooks).forEach(function(notebook){
            locals.sidebar.items.push(notebook.title);
        });
        //console.log(locals.sidebar.items);
        var activeNotebooks= _.filter(notebooks,function(notebook){
            return notebook.isActive;
        });
        var notes=activeNotebooks[0].notes;
        notesCollection.find({_id:{$in:notes}},function(err,docs){
            if(err)
                console.error(err);
            else
            {
                if(docs.length)
                {
                    locals.notebook.notes=docs;
                    console.dir(locals);
                    res.render('main',locals);
                }   
            }   
        });
    }       
});