1

Currently I have a problem with fetching data. I want to get data from database and print it with pug template Here is code from my index.js where I get data from collection and putting in to array.

//Printing a lesson
 router.get('/getLesson', function(req,res, next){
     var resultArray = [];
     mongo.connect(url, function(err, db){
         assert.equal(null,err);
         var cursor = db.collection('lesson-data').find();
         cursor.forEach(function(doc, err){
             assert.equal(null, err);
             resultArray.push(doc);
         }, function(){
             db.close();
             res.render('lessons', {item: resultArray});
         });
     });
 });

//Inserting a lesson
router.post('/lessonInsert', function(req,res,next){
    var lesson = {
        topic: req.body.topic,
        description: req.body.description,
        language: req.body.language,
        level: req.body.level
    };

    mongo.connect(url,function(err, db){
        assert.equal(null,err);
        db.collection('lesson-data').insertOne(lesson, function(err, result){
            assert.equal(null, err);
            console.log('Lesson inserted');
            db.close();
        })
    })
});

There I was trying to print my array.

.container(action='/getLesson')        
  each item in resulArray
    li #{item.topic}: #{item.description}: #{item.language}: #{item.level}

Any tips, help?

1 Answers1

1

When you do the following:

res.render('lessons', {item: resultArray})

you are actually passing the variable resultArray named as item to you pug template. So the iteration would be:

.container(action='/getLesson')        
  each element in item
    li #{element.topic}: #{element.description}: #{element.language}: #{element.level}
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • When I put this part of code .container(action='/getLesson') each element in item li #{element.topic}: #{element.description}: #{element.language}: #{element.level}, I get an error: Error: Failed to lookup view "error" in views directory. Any ideas why? – Simon Draymon Mar 21 '17 at 18:49