【问题标题】:trying to display data in jade from mongodb试图从 mongodb 显示玉中的数据
【发布时间】:2016-12-20 02:54:41
【问题描述】:

试图将数据从猫鼬模式显示到玉模板,但无论我尝试什么都不起作用,所以请帮助我并感谢。

首先是我的书本模式 models/book.js

  const mongoose = require('mongoose')
const schema = mongoose.Schema

const BookSchema = new schema({
  title: String,
  author: String,
  isbn: Number,
  date: { type: Date, default: Date.now},
  description: String
})


module.exports = mongoose.model('Book', BookSchema)

这是我的书本模型控制器

    const Book = require('../models/book')
const express = require('express')
router = express.Router()


router.route('/books')
  // Create a book
  .post( (req, res) => {
    const book = new Book()
    book.name = req.body.name

    book.save( (err) => {
      if (err)
        res.send(err)

      console.log('Book created! ')
    })
  })

  //get all books
  .get( (req, res) => {
    Book.find( (err, books) => {
      if (err)
        res.send(err)

      res.render('books', {title: 'books list'})
    })
  })




module.exports = router

最后这是我的玉石模板

    extends layout

block content
  if books
    each book in books
      h1 #{book.title}

【问题讨论】:

  • 正如 Ravi 在下面指出的那样,您需要在您的 res.render 呼叫中发送 books 才能在您的模板中使用它。休息很好。

标签: node.js mongodb express mongoose pug


【解决方案1】:

您的代码中有多个错误/修改。

  1. 在查找时,最好将{} 作为第一个输入。

  2. 在渲染书籍模板时,您使用books 变量来显示书籍列表,但不是从路由发送。您需要在res.render 中发送books

试试这个:

router.route('/books')
  // Create a book
  .post( (req, res) => { 
    const book = new Book()
    book.name = req.body.name

    book.save( (err) => {
        res.send(err)

      console.log('Book created! ')
    })
  })

  //get all books
  .get((req, res) => {
    Book.find({},(err, books) => { 
      if (err)
        res.send(err)

      res.render('books', {title: 'books list' , books : books})//need to send the books variable to the template.
    })
  })

【讨论】:

  • 他们对箭头函数的使用是正确的。如果指定function 关键字,则不需要箭头。
猜你喜欢
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 2015-08-20
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
相关资源
最近更新 更多