Question

I am building a web app with express, nodejs and monk. I am trying to create a page for each element of an array in my mongodb database.

That data is already in the collection called collections with the key coll_list like so:

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

I thought it might be possible to loop over all the elements in coll_list with something like:

 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
         });
       }
     });
 });

Any suggestions or help/pointers on how to do this would be greatly appreciated.

Was it helpful?

Solution

Use 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. 

  });

Thus, using a single route you would be able to create a page for every item in coll_list

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top