0

我正在用 express、nodejs 和僧侣构建一个网络应用程序。我正在尝试为我的 mongodb 数据库中数组的每个元素创建一个页面。

该数据已经在名为collections的集合中,其键为 coll_list,如下所示:

{ "_id" : ObjectId("53dbaefd3d85d57492506f1f"), "coll_list" : [     "data_pagename1", 
     "data_pagename2", "data_pagename3" ] }

我认为可以循环遍历coll_list中的所有元素,例如:

 router.get('/index', function(req, res) {
     var db = req.db;
     var collection = db.get('collections');
     collection.find( "coll_list" , function(e,docs) {
       for (elems in docs) {
         res.render(elems, {
           elems : docs
         });
       }
     });
 });

任何有关如何执行此操作的建议或帮助/指示将不胜感激。

4

1 回答 1

1

使用req.params

router.get('/coll/:id',
  function(req,res){
     //access the id by req.params.id
     //req.params.id will essentially be the _id of the document
     //use it to obtain data from mongoDB and render the page using that data
     //From the front end you make the call to /coll/<ObjectId> like
     // /coll/53dbaefd3d85d57492506f1f and you get that id in req.params.id and use it to
     //render data specific to that _id. 

  });

因此,使用单个路由,您将能够为中的每个项目创建一个页面coll_list

于 2014-08-01T17:10:42.753 回答