title: Dynamic CRUD functions with Node, Express and Pug
body: <p>Hi I am new to backend node applications and I am trying to create a clean API driven node.js app without frameworks by working with scripts and pug template engine.</p>
  
  <p>I have created a <code>serve.js</code> file with all the necessary code:</p>
  
  <pre><code>var express = require('express');
  var app = express();
  var path = require('path');
  var favicon = require('serve-favicon');
  const bodyParser = require("body-parser");
  var mongodb = require("mongodb");
  const MongoClient = require('mongodb').MongoClient
  var ObjectID = mongodb.ObjectID;
  var indexRoutes = require('./routes/index');
  var thePort = process.env.PORT || 5000;
  
  
  var SECTIONS_COLLECTION = "sections";
  
  //make results available as json
  app.use(bodyParser.json());
  
  //External database identifier
  var db;
  
  //Path to the database with URI
  var dbpath =  process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2orjhen7knanjpfmd7@ds014586.mlab.com:19986/heroku_fmvc5nhk';
  
  // Connect to the database before starting the application server.
  mongodb.MongoClient.connect(dbpath, function (err, database) {
    if (err) {
      console.log(err);
      process.exit(1);
    }
  
  // Save database object from the callback for reuse.
  db = database;
  console.log("Database connection ready");
  
  //static folder directory
  app.use(express.static(__dirname + '/dist'));
  
  // Initialize the app.
  var server = app.listen(process.env.PORT || thePort, function () {
      var port = server.address().port;
      console.log("App now running on port", port);
    });
  });
  
  // Generic error handler used by all endpoints.
  function handleError(res, reason, message, code) {
    console.log("ERROR: " + reason);
    res.status(code || 500).json({"error": message});
  }
  
  
  //set up routes directory
  app.use('/', indexRoutes);
  
  // Views and Template Engine
  //app.set('views', __dirname + './views');
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'pug');
  
  
  // sections API ROUTES:
  
  /*  "/api/sections"
   *    GET: finds all sections
   *    POST: creates a new contact
   */
  
   app.get("/api/sections", function(req, res) {
     db.collection(SECTIONS_COLLECTION).find({}).toArray(function(err, docs) {
       if (err) {
         handleError(res, err.message, "Failed to get sections.");
       } else {
         res.status(200).json(docs);
       }
     });
   });
  
  app.post("/api/sections", function(req, res) {
    var newContact = req.body;
  
    if (!req.body.name) {
      handleError(res, "Invalid user input", "Must provide a name.", 400);
    }
  
    db.collection(sections_COLLECTION).insertOne(newContact, function(err, doc) {
      if (err) {
        handleError(res, err.message, "Failed to create new contact.");
      } else {
        res.status(201).json(doc.ops[0]);
      }
    });
  });
  
  /*  "/api/sections/:id"
   *    GET: find contact by id
   *    PUT: update contact by id
   *    DELETE: deletes contact by id
   */
  
   app.get("/api/sections/:id", function(req, res) {
     db.collection(SECTIONS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
       if (err) {
         handleError(res, err.message, "Failed to get contact");
       } else {
         res.status(200).json(doc);
       }
     });
   });
  
   app.put("/api/sections/:id", function(req, res) {
     var updateDoc = req.body;
     delete updateDoc._id;
  
     db.collection(SECTIONS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
       if (err) {
         handleError(res, err.message, "Failed to update contact");
       } else {
         updateDoc._id = req.params.id;
         res.status(200).json(updateDoc);
       }
     });
   });
  
   app.delete("/api/sections/:id", function(req, res) {
     db.collection(SECTIONS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
       if (err) {
         handleError(res, err.message, "Failed to delete contact");
       } else {
         res.status(200).json(req.params.id);
       }
     });
   });
  </code></pre>
  
  <p>In my <code>views\about.pug</code> template I reference my JSON object's contents.</p>
  
  <pre><code>//--about.pug
  extends index.pug
  
  block div.root
    h2= #{about.heading}
    h3= #{about.summary}
    p   #{about.content}
  </code></pre>
  
  <p>In my routes<code>routes/index.js</code> I have pre-existing "flat" examples with pug then one dynamic <code>about</code> example:</p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
    router.get('/', function (req, res) {
          res.render(
              'index',
              {
                title: 'Welcome to Awesome Place',
                header: 'Home',
                summary: 'This is my home. It can\'t be any simpler'
              }
          )
      })
  </code></pre>
  
  <p>Dynamic example:</p>
  
  <pre><code>   //About
          router.get('/about', function (req, res) {
              //retrieve all home from Mongo
              db.collection(SECTIONS_COLLECTION).find({"name": "about"}), function (err, about) {
  
                if (err) {
                  handleError(res, err.message, "Failed to get sections.");
                } else {
                     res.render('about', {})
                    console.log(result)
                }
  
              }
            })
  </code></pre>
  
  <p>The above is returning a <code>db is not defined</code> error. </p>
  
  <p>If <code>var indexRoutes = require('./routes/index');</code> is required as part of my server.js file, why can't it find the value of db?</p>
  
  <p>UPDATED CODE (TOO MANY ERRORS)</p>
  
  <p>//server.js</p>
  
  <pre><code>//APP Dependences
  var express       = require('express');
  var app           = express();
  var path          = require('path');
  var favicon       = require('serve-favicon');
  var indexRoutes   = require('./routes/index');
  var bodyParser    = require("body-parser");
  
  //PORT
  var thePort = process.env.PORT || 5000;
  
  // Views and Template Engine
  //app.set('views', __dirname + './views');
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'pug');
  
  //Documents
  app.use(bodyParser.json());
  //static folder directory
  app.use(express.static(__dirname + '/dist'));
  
  
  //set up routes directory
  app.use('/', indexRoutes);
  
  // Catch errors
  app.use(function(req, res, next) {
    res.status(404).sendFile(process.cwd() + '/app/views/404.htm');
  });
  
  
  // Initialize the app.
  var server = app.listen(process.env.PORT || thePort, function () {
      var port = server.address().port;
      console.log("App now running on port", port);
    });
  });
  
  var mongodb = require("mongodb");
  const MongoClient = require('mongodb').MongoClient
  var ObjectID = mongodb.ObjectID;
  
  
  var SECTIONS_COLLECTION = "sections";
  
  
  
  //External database identifier
  var db;
  
  //Path to the database with URI
  var dbpath =  process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2ovanbfd7knanjpfmd7@ds019986.mlab.com:19986/heroku_fmvc5nhk';
  
  // Connect to the database before starting the application server.
  mongodb.MongoClient.connect(dbpath, function (err, database) {
    if (err) {
      console.log(err);
      process.exit(1);
    }
  
  // Save database object from the callback for reuse.
  db = database;
  console.log("Database connection ready");
  
  
  // Initialize the app.
  var server = app.listen(process.env.PORT || thePort, function () {
      var port = server.address().port;
      console.log("App now running on port", port);
    });
  
  // Generic error handler used by all endpoints.
  function handleError(res, reason, message, code) {
    console.log("ERROR: " + reason);
    res.status(code || 500).json({"error": message});
  }
  </code></pre>
  
  <p>//db.js</p>
  
  <pre><code>var express       = require('express');
  var mongodb       = require("mongodb");
  var MongoClient   = require('mongodb').MongoClient
  var ObjectID      = mongodb.ObjectID;
  var assert        = require('assert');
  
  //Path to the database with
  var dbpath =  process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2ovahen7knanjpfmd7@ds019986.mlab.com:19986/heroku_fmvc5nhk';
  
  //Get the section
  var SECTIONS_COLLECTION = "sections";
  
  // Use connect method to connect to the server
  var database;
  
  function connectMongo(cb){
      MongoClient.connect(dbpath , function(err, database) {
        assert.equal(null, err);
        console.log("Connected successfully to server");
  
        cb(database);
      });
  }
  
  module.exports = connectMongo;
  </code></pre>
  
  <p>//routes/index.js</p>
  
  <pre><code>var express       = require('express');
  var router        = express.Router();
  var connectDB     = require ('../db')
  
  
  
  
    router.get('/', function (req, res) {
          res.render(
              'index',
              {
                title: 'Welcome to Awesome Place',
                header: 'Home',
                summary: 'This is my home. It can\'t be any simpler'
              }
          )
      })
  
  connectMongo(function(database){
      //About
          router.get('/about', function (req, res) {
              //retrieve all home from Mongo
              database.collection(SECTIONS_COLLECTION).find({"name": "about"}), function (err, about) {
  
                if (err) {
                  handleError(res, err.message, "Failed to get sections.");
                } else {
                     res.render('about', {})
                    console.log(result)
                }
  
              }
            })
    }
  
  
      router.get('/work', function (req, res) {
          res.render(
              'work',
              {
                title: 'Work, Work, Work , Work...',
                header: 'Work life',
                summary: 'My first work for this bitch',
                imgUrl: '/img/firaz.jpg'
              }
          )
      })
  
      router.get('/contact', function (req, res) {
          res.render(
              'contact',
              {
                title: 'Contact Me Any Time',
                header: 'Contact Me Any Time',
                summary: 'Fill the form below to be contacted'
              }
          )
      })
  module.exports = router;
  </code></pre>