无法从MongoDB中检索数据并在Node和Express中显示在.hbs文件中。

huangapple go评论66阅读模式
英文:

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(&quot;path&quot;);
const hbs = require(&quot;hbs&quot;);
const session = require(&#39;express-session&#39;);             //admin 
const adminRoutes = require(&#39;../routes/admin&#39;);
const bodyParser = require(&quot;body-parser&quot;);
const mongoose = require(&quot;mongoose&quot;);
mongoose.set(&#39;strictQuery&#39;, false);
const app = express();
const port = process.env.PORT || 3000;
//setting path
const viewpath = path.join(__dirname, &quot;../templates/views&quot;);
const partialspath = path.join(__dirname, &quot;../templates/partials&quot;);
app.set(&quot;view engine&quot;, &quot;hbs&quot;);
app.set(&quot;partial engine&quot;, &quot;hbs&quot;);
app.set(&quot;views&quot;, viewpath);
app.set(&quot;partials&quot;, partialspath);
hbs.registerPartials(partialspath);
app.use(bodyParser.json());
app.use(express.static(&#39;public&#39;));
app.use(bodyParser.urlencoded({ extended: true }));
//Add Book
const db3 = mongoose.createConnection(&#39;mongodb://127.0.0.1:27017/Book&#39;);
const Book = require(&#39;./models/book&#39;);
db3.on(&#39;error&#39;, () =&gt; console.log(&quot;error in connection&quot;));
db3.once(&#39;open&#39;, () =&gt; {console.log(&quot;connected successfully to Book database&quot;);});
app.post(&#39;/books&#39;, async (req, res) =&gt; {
const { skill, title, author, pages, link } = req.body;
const book = new Book({
skill,
title,
author,
pages,
link,
});
await book.save();
res.redirect(&#39;/admin/dashboard&#39;);
console.log(&quot;Book added by Admin&quot;);
});
//Fetch Book  
app.get(&#39;/ubooks&#39;, (req, res) =&gt; {
Book.find({}, &#39;skill title author pages link&#39;, (err, books) =&gt; {
if (err) {
console.error(err);
console.log(&quot;hii err&quot;);
return res.status(500).send(&#39;Error fetching books from database&#39;);
}
console.log(&quot;hii&quot;);
res.render(&#39;ubooks&#39;, { books });
});
});
//This is my ubooks.hbs file where i want to display fetched data:
&lt;html&gt;
&lt;body&gt;
{{#each books}}
&lt;div&gt;
&lt;h2&gt;Skill: {{this.skill}}&lt;/h2&gt;
&lt;h2&gt;Title: {{this.title}}&lt;/h2&gt;
&lt;p&gt;Author: {{this.author}}&lt;/p&gt;
&lt;h2&gt;Pages: {{this.pages}}&lt;/h2&gt;
&lt;h2&gt;Link: {{this.link}}&lt;/h2&gt;
&lt;/div&gt;
{{/each}}
&lt;/body&gt;
&lt;/html&gt;````
</details>
# 答案1
**得分**: 1
`mongoose`不再支持模型API方法的回调方式。&lt;br&gt;
尝试使用`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.&lt;br&gt;
Try with `async await`:
```
app.get(&#39;/ubooks&#39;, async (req, res) =&gt; {
try {
const books = await Book.find({}, &#39;skill title author pages link&#39;).exec();
res.render(&#39;ubooks&#39;, { books });
} catch (err) {
console.error(err);
return res.status(500).send(&#39;Error fetching books from database&#39;);
}
});
```
</details>

huangapple
  • 本文由 发表于 2023年4月7日 03:02:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定