【问题标题】:fetch data from mongodb with template pug using node.js使用 node.js 使用模板 pug 从 mongodb 获取数据
【发布时间】:2017-08-13 14:12:20
【问题描述】:

目前我在获取数据时遇到问题。我想从数据库中获取数据并用 pug 模板打印 这是我的 index.js 中的代码,我在其中从集合中获取数据并放入数组。

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

在那里我试图打印我的数组。

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

任何提示,帮助?

【问题讨论】:

    标签: javascript node.js mongodb pug


    【解决方案1】:

    当您执行以下操作时:

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

    您实际上是在将名为item 的变量resultArray 传递给您的哈巴狗模板。所以迭代将是:

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

    【讨论】:

    • 当我把这部分代码 .container(action='/getLesson') 每个元素在项目 li #{element.topic}: #{element.description}: #{element.language} :#{element.level},我收到一个错误:错误:无法在视图目录中查找视图“错误”。任何想法为什么?
    猜你喜欢
    • 1970-01-01
    • 2020-01-13
    • 2020-09-27
    • 2014-05-18
    • 2019-10-14
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    相关资源
    最近更新 更多