كيفية التكرار على مصفوفة mongodb باستخدام Express وMonk لإنشاء صفحة لكل عنصر؟

StackOverflow https://stackoverflow.com//questions/25084422

  •  02-01-2020
  •  | 
  •  

سؤال

أقوم بإنشاء تطبيق ويب باستخدام Express وNodejs وMonk.أحاول إنشاء صفحة لكل عنصر من عناصر المصفوفة في قاعدة بيانات mongodb الخاصة بي.

هذه البيانات موجودة بالفعل في المجموعة المسماة مجموعات مع المفتاح 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
         });
       }
     });
 });

أي اقتراحات أو مساعدة/مؤشرات حول كيفية القيام بذلك سيكون موضع تقدير كبير.

هل كانت مفيدة؟

المحلول

يستخدم 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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top