0

I'm working on c9 (cloud 9) using node.js, express, body-parser and ejs. I installed all packages and have database configured and with blogs collection containing data; however, when I run the app in the browser, I get this error:

The error let's me know that "blogs" is not defined. However, I'm passing it from app.js

I can't figure out why index.ejs page can't see the "blogs" variable. Here's my app.js file

var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var express = require("express");
var app = express();

//app configuration
mongoose.connect("mongodb://localhost/restful_blog_app");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));

//schema
var blogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body:  String,
    created: {type: Date, default: Date.now}
})

var Blog = mongoose.model("Blog", blogSchema);

Blog.create({
    title: "Test Blog",
    image: "http://cushingsindogs.com/wp-content/uploads/2018/02/CID-website-Survey-Page.jpg",
    body: "Hello this is a blog post!"
})

// RESTFUL ROUTES
app.get("/", function(req, res) {
    res.redirect("/blogs")
})

app.get("/blogs", function(req, res) {
    Blog.find({}, function(err, blogs) {
        if(err) console.log(err)
        else {
            console.log(blogs);
            res.render("index", {blogs: blogs});
        }
    })
    res.render("index")
})

//server listening
app.listen(process.env.PORT, process.env.IP, function() {
    console.log("Server Running on port "+process.env.PORT);
});

index.ejs file

<h1>INDEX PAGE</h1>

<% blogs.forEach(function(blog) { %>
    <div>
        <h2><%= blog.title %></h2>
        <img src="<%= blog.image %>">
        <span><%= blog.created %></span>
        <p><%= blog.body %></p>
    </div>
<% }); %>
miatech
  • 2,150
  • 8
  • 41
  • 78

2 Answers2

0

Remove res.render('index');. It's being called before Blog.find({}, ...) completes. Remember, Blog.find({}, ...) is asynchronous.

Mikey
  • 6,728
  • 4
  • 22
  • 45
0

All Database operations are asynchronous. You have to remove the res.render("index"). It's not needed.

Bharathvaj Ganesan
  • 3,054
  • 1
  • 18
  • 32