英文:
Not able to fetch data from mongodb and display in .hbs file using node and express
问题
上面的hbs文件没有获取数据
这里每个块中的整个代码都没有显示
我无法理解出现了什么问题,因为它没有抛出任何错误
而在添加书籍时没有问题,书籍已经添加到了MongoDB中。但无法从MongoDB中获取数据
帮我处理代码
我的app.js文件:
const express = require("express");
const path = require("path");
const hbs = require("hbs");
const session = require('express-session'); //admin
const adminRoutes = require('../routes/admin');
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.set('strictQuery', false);
const app = express();
const port = process.env.PORT || 3000;
//设置路径
const viewpath = path.join(__dirname, "../templates/views");
const partialspath = path.join(__dirname, "../templates/partials");
app.set("view engine", "hbs");
app.set("partial engine", "hbs");
app.set("views", viewpath);
app.set("partials", partialspath);
hbs.registerPartials(partialspath);
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
//添加书籍
const db3 = mongoose.createConnection('mongodb://127.0.0.1:27017/Book');
const Book = require('./models/book');
db3.on('error', () => console.log("连接错误"));
db3.once('open', () => {console.log("成功连接到Book数据库");});
app.post('/books', async (req, res) => {
const { skill, title, author, pages, link } = req.body;
const book = new Book({
skill,
title,
author,
pages,
link,
});
await book.save();
res.redirect('/admin/dashboard');
console.log("管理员添加书籍");
});
//获取书籍
app.get('/ubooks', (req, res) => {
Book.find({}, 'skill title author pages link', (err, books) => {
if (err) {
console.error(err);
console.log("出错了");
return res.status(500).send('从数据库获取书籍时出错');
}
console.log("嗨");
res.render('ubooks', { books });
});
});
//这是我的ubooks.hbs文件,我希望在其中显示获取的数据:
<html>
<body>
{{#each books}}
<div>
<h2>技能:{{this.skill}}</h2>
<h2>标题:{{this.title}}</h2>
<p>作者:{{this.author}}</p>
<h2>页数:{{this.pages}}</h2>
<h2>链接:{{this.link}}</h2>
</div>
{{/each}}
</body>
</html>
英文:
The above hbs file is not fetching data
Here the whole code inside each block is not being displayed
Here I'm not able to understand what's wrong cause it's not throwing any error
And there's no problem while adding books, books are added in mongoDB. But from MongoDB not able to fetch data
Help me with code
My app.js file:
const path = require("path");
const hbs = require("hbs");
const session = require('express-session'); //admin
const adminRoutes = require('../routes/admin');
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.set('strictQuery', false);
const app = express();
const port = process.env.PORT || 3000;
//setting path
const viewpath = path.join(__dirname, "../templates/views");
const partialspath = path.join(__dirname, "../templates/partials");
app.set("view engine", "hbs");
app.set("partial engine", "hbs");
app.set("views", viewpath);
app.set("partials", partialspath);
hbs.registerPartials(partialspath);
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
//Add Book
const db3 = mongoose.createConnection('mongodb://127.0.0.1:27017/Book');
const Book = require('./models/book');
db3.on('error', () => console.log("error in connection"));
db3.once('open', () => {console.log("connected successfully to Book database");});
app.post('/books', async (req, res) => {
const { skill, title, author, pages, link } = req.body;
const book = new Book({
skill,
title,
author,
pages,
link,
});
await book.save();
res.redirect('/admin/dashboard');
console.log("Book added by Admin");
});
//Fetch Book
app.get('/ubooks', (req, res) => {
Book.find({}, 'skill title author pages link', (err, books) => {
if (err) {
console.error(err);
console.log("hii err");
return res.status(500).send('Error fetching books from database');
}
console.log("hii");
res.render('ubooks', { books });
});
});
//This is my ubooks.hbs file where i want to display fetched data:
<html>
<body>
{{#each books}}
<div>
<h2>Skill: {{this.skill}}</h2>
<h2>Title: {{this.title}}</h2>
<p>Author: {{this.author}}</p>
<h2>Pages: {{this.pages}}</h2>
<h2>Link: {{this.link}}</h2>
</div>
{{/each}}
</body>
</html>````
</details>
# 答案1
**得分**: 1
`mongoose`不再支持模型API方法的回调方式。<br>
尝试使用`async await`:
```javascript
app.get('/ubooks', async (req, res) => {
try {
const books = await Book.find({}, 'skill title author pages link').exec();
res.render('ubooks', { books });
} catch (err) {
console.error(err);
return res.status(500).send('从数据库获取书籍时出错');
}
});
```
<details>
<summary>英文:</summary>
`mongoose` no longer supports callbacks for Model API methods.<br>
Try with `async await`:
```
app.get('/ubooks', async (req, res) => {
try {
const books = await Book.find({}, 'skill title author pages link').exec();
res.render('ubooks', { books });
} catch (err) {
console.error(err);
return res.status(500).send('Error fetching books from database');
}
});
```
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论