问题
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.
while finding, its better to give
{}
as first input.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 sendbooks
inres.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