【问题标题】:NodeJS, Express, PUG - Need to render results from mongo db to variables contained in pug viewNodeJS、Express、PUG - 需要将结果从 mongo db 渲染到 pug 视图中包含的变量
【发布时间】:2017-08-01 03:42:25
【问题描述】:

我有一个网站,用于保存文件和通过表格标记条目。我目前正在尝试查找 mongo 集合中的所有文档,然后使用 res.render() 方法填充 documents.pug 中的变量。

我尝试将res.render 放在for 循环中,然后将var i 传递给我的结果参数。经过一番阅读,我发现我不能多次执行res.render(for循环。)。

我有一个使用猫鼬的模型设置。我能够找到集合中的所有文档并返回它们。我的问题是用Documents.find({})(mongoose) 返回的结果填充我通过res.render() 定义的pug 变量。

谁能帮我找出解决办法?


文档.js

module.exports = (app) => {
  // Creating new instance of router for docsPage.
  const docsRouter = require('express').Router();

  // Creating Document const which will contain the documents model schema.
  const Document = require('../models/document.model');

  docsRouter.route('/')

  .get((req, res) => {
    Document.find((err, docs) => {
      if (err) {
        console.error(err);
        res.send(err);
      }
      else {
        // console.log(docs[0].doc_id);
        res.render('documents', {
          pageTitle: "Documents",
          doc_id: docs.doc_id,
          doc_title: docs.doc_title,
          doc_category: docs.doc_category,
          doc_author: docs.doc_author,
          doc_description: docs.doc_description
        });
      }
    });
  })

  app.use('/documents', docsRouter);
}

文件.pug


extends layout

block main
  div(class="container")
    table(class="uk-table uk-table-striped uk-table-small")
      thead
        tr
          th Document ID
          th Title
          th Category
          th Author
          th Description
      tfoot
      tbody
        - for (var i = 0; i < 5; ++i)
          tr
            td= doc_id
            td= doc_title
            td= doc_category
            td= doc_author
            td= doc_description

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    您正在呈现带有未定义值的表单,因为 docs 是一个数组,而数组不会有 Document 属性。

    res.render 更改为

    res.render('documents', {
         pageTitle: "Documents",
         docs: docs
    });
    

    和帕格观点:

    extends layout
    
    block main
      div(class="container")
        table(class="uk-table uk-table-striped uk-table-small")
          thead
            tr
              th Document ID
              th Title
              th Category
              th Author
              th Description
          tfoot
          tbody
            - each doc in docs
              tr
                td= doc.doc_id
                td= doc.doc_title
                td= doc.doc_category
                td= doc.doc_author
                td= doc.doc_description
    

    【讨论】:

    • 啊,天哪……这更有意义。 :) 我认为是时候退后一步,多想想了。非常感谢@hya!这就像一个魅力。
    猜你喜欢
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多