title: NodeJS image not uploading and category name showing variable instead of value
body: <p>I am working on a NodeJS style blog and for some reason, the variable for the category name shows up as #{category.name} whereas the other variable values actually show the values. Secondly, When I submit the image for the post, it does not upload the image. Any help to see if there might be some errors in my code would be greatly appreciated. Thank you in advance.</p>
  
  <p><a href="https://i.stack.imgur.com/qDFvW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qDFvW.png" alt="screenshot of variable in place of value"></a>
  <a href="https://i.stack.imgur.com/QqMb0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QqMb0.png" alt="screenshot of dev tools error"></a></p>
  
  <p>app.js</p>
  
  <pre><code>var express = require("express");
  var path = require("path");
  var favicon = require("serve-favicon");
  var logger = require("morgan");
  var cookieParser = require("cookie-parser");
  var bodyParser = require("body-parser");
  var session = require("express-session");
  var multer = require("multer");
  var upload = multer({ dest: "./public/images" });
  var expressValidator = require("express-validator");
  
  var mongo = require("mongodb");
  var db = require("monk")("localhost/nodeblog");
  
  var routes = require("./routes/index");
  var posts = require("./routes/posts");
  var categories = require("./routes/categories");
  
  var app = express();
  
  app.locals.moment = require("moment");
  
  app.locals.truncateText = function(text, length) {
    var truncatedText = text.substring(0, length);
    return truncatedText;
  };
  
  // view engine setup
  app.set("views", path.join(__dirname, "views"));
  app.set("view engine", "pug");
  
  // uncomment after placing your favicon in /public
  //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
  app.use(logger("dev"));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, "public")));
  
  // Express Session
  app.use(
    session({
      secret: "secret",
      saveUninitialized: true,
      resave: true
    })
  );
  
  // Express Validator
  app.use(
    expressValidator({
      errorFormatter: function(param, msg, value) {
        var namespace = param.split("."),
          root = namespace.shift(),
          formParam = root;
  
        while (namespace.length) {
          formParam += "[" + namespace.shift() + "]";
        }
        return {
          param: formParam,
          msg: msg,
          value: value
        };
      }
    })
  );
  
  // Connect-Flash
  app.use(require("connect-flash")());
  app.use(function(req, res, next) {
    res.locals.messages = require("express-messages")(req, res);
    next();
  });
  
  // Make our db accessible to our router
  app.use(function(req, res, next) {
    req.db = db;
    next();
  });
  
  app.use("/", routes);
  app.use("/posts", posts);
  app.use("/categories", categories);
  
  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
    var err = new Error("Not Found");
    err.status = 404;
    next(err);
  });
  
  // error handlers
  
  // development error handler
  // will print stacktrace
  if (app.get("env") === "development") {
    app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render("error", {
        message: err.message,
        error: err
      });
    });
  }
  
  // production error handler
  // no stacktraces leaked to user
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render("error", {
      message: err.message,
      error: {}
    });
  });
  
  module.exports = app;
  </code></pre>
  
  <p>index.pug</p>
  
  <pre><code>extends layout
  
  block content
    if posts
     each post, i in posts
      .post
       h1
        a(href='/posts/show/#{post._id}')
         =post.title
       p.meta Posted in 
        a(href='/categories/show/#{post.category}') #{post.category} by #{post.author} on #{moment(post.date).format("MM-DD-YYYY")}
       img(src='/images/#{post.mainimage}')
       !=truncateText(post.body,400)
       a.more(href='/posts/show/#{post._id}') Read More
  </code></pre>
  
  <p>addpost.pug</p>
  
  <pre><code>extends layout
  
  block content
      h1=title
      ul.errors
          if errors
              each error, i in errors
                  li.alert.alert-danger #{error.msg}
      form(method='post', action='/posts/add', enctype="multipart/form-data")
          .form-group
              label Title:
              input.form-control(name='title', type='text')
          .form-group
              label Category
              select.form-control(name='category')
                  each category, i in categories
                      option(value='#{category.name}') #{category.name}
          .form-group
              label Body
              textarea.form-control(name='body', id='body')
          .form-group
              label Main Image:
              input.form-control(name='mainimage', type='file')
          .form-group
              label Author:
              select.form-control(name='author')
                  option(value='Erik Robles') Erik Robles
                  option(value='John Doe') John Doe
          input.btn.btn-default(name='submit',type='submit',value='Save')
          script(src='/ckeditor/ckeditor.js')
          script
              | CKEDITOR.replace('body');
  </code></pre>
  
  <p>addcategory.pug</p>
  
  <pre><code>extends layout
  
  block content
      h1=title
      ul.errors
          if errors
              each error, i in errors
                  li.alert.alert-danger #{error.msg}
      form(method='post', action='/categories/add')
          .form-group
              label Name:
              input.form-control(name='name', type='text')
          input.btn.btn-default(name='submit',type='submit',value='Save')
  </code></pre>
  
  <p>posts.js</p>
  
  <pre><code>var express = require("express");
  var router = express.Router();
  var multer = require("multer");
  var upload = multer({ dest: "./public/images" });
  var mongo = require("mongodb");
  var db = require("monk")("localhost/nodeblog");
  
  router.get("/add", function(req, res, next) {
    var categories = db.get("categories");
  
    categories.find({}, {}, function(err, categories) {
      res.render("addpost", {
        title: "Add Post",
        categories: categories
      });
    });
  });
  
  router.post("/add", upload.single("mainimage"), function(req, res, next) {
    // Get Form Values
    var title = req.body.title;
    var category = req.body.category;
    var body = req.body.body;
    var author = req.body.author;
    var date = new Date();
  
    // Check Image Upload
    if (req.file) {
      var mainimage = req.file.filename;
    } else {
      var mainimage = "noimage.jpg";
    }
  
    // Form Validation
    req.checkBody("title", "Title field is required").notEmpty();
    req.checkBody("body", "Body field is required").notEmpty();
  
    // Check Errors
    var errors = req.validationErrors();
  
    if (errors) {
      res.render("addpost", {
        errors: errors
      });
    } else {
      var posts = db.get("posts");
      posts.insert(
        {
          title: title,
          body: body,
          category: category,
          date: date,
          author: author,
          mainimage: mainimage
        },
        function(err, post) {
          if (err) {
            res.send(err);
          } else {
            req.flash("success", "Post Added");
            res.location("/");
            res.redirect("/");
          }
        }
      );
    }
  });
  
  module.exports = router;
  </code></pre>
  
  <p>index.js</p>
  
  <pre><code>var express = require("express");
  var router = express.Router();
  var mongo = require("mongodb");
  var db = require("monk")("localhost/nodeblog");
  
  /* GET home page. */
  router.get("/", function(req, res, next) {
    var db = req.db;
    var posts = db.get("posts");
    posts.find({}, {}, function(err, posts) {
      res.render("index", { posts: posts });
    });
  });
  
  module.exports = router;
  </code></pre>
  
  <p>categories.js</p>
  
  <pre><code>var express = require("express");
  var router = express.Router();
  var mongo = require("mongodb");
  var db = require("monk")("localhost/nodeblog");
  
  router.get("/show/:category", function(req, res, next) {
    var posts = db.get("posts");
  
    posts.find({ category: req.params.category }, {}, function(err, posts) {
      res.render("index", {
        title: req.params.category,
        posts: posts
      });
    });
  });
  
  router.get("/add", function(req, res, next) {
    res.render("addcategory", {
      title: "Add Category"
    });
  });
  
  router.post("/add", function(req, res, next) {
    // Get Form Values
    var name = req.body.name;
  
    // Form Validation
    req.checkBody("name", "Name field is required").notEmpty();
  
    // Check Errors
    var errors = req.validationErrors();
  
    if (errors) {
      res.render("addpost", {
        errors: errors
      });
    } else {
      var categories = db.get("categories");
      categories.insert(
        {
          name: name
        },
        function(err, post) {
          if (err) {
            res.send(err);
          } else {
            req.flash("success", "Category Added");
            res.location("/");
            res.redirect("/");
          }
        }
      );
    }
  });
  
  module.exports = router;
  </code></pre>
  
  <p>If I am missing anything, please let me know so I can make the appropriate edits. Again, Thank you.
  P.S. By structure is:</p>
  
  <pre><code>routes
   categores.js
   index.js
   posts.js
  views
   addcategory.pug
   addpost.pug
   error.pug
   index.pug
   layout.pug
  app.js
  </code></pre>