trying to display data in jade from mongodb

我的梦境 提交于 2020-01-03 05:54:13

问题


trying to display data from mongoose schema to jade temaplate but it dosent work no matter what i try , so please help me and thanks .

first here is my book schema 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)

and here is my controller for the book model

    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

and at last here is my jade template

    extends layout

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

回答1:


There are multiple mistakes/modifications required in your code.

  1. while finding, its better to give {} as first input.

  2. When rendering the book template, you are using books variable to show list of books, but you are not sending it from the route. you need to send books in res.render.

Try this:

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.
    })
  })


来源:https://stackoverflow.com/questions/38929034/trying-to-display-data-in-jade-from-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!