Search code examples
node.jsmongodbexpressmongoosehbs

Not able to fetch data from mongodb and display in .hbs file using node and express


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>````

Solution

  • mongoose no longer supports callbacks for Model API methods.

    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');
      }
    });