WebFund 2016W Lecture 12

From Soma-notes
Revision as of 22:26, 25 February 2016 by Soma (talk | contribs)

Video

The video for the lecture given on February 25, 2016 is now available.

Notes

Code

Below is examforms.js modified to have MongoDB support. You can also download the full version.

var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var port = 3000;

var mc = require('mongodb').MongoClient;
var db, formsCollection;

var state = [];

var app = express();

app.set('view engine', 'jade');
app.set('views', __dirname);
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));


var connectCallback = function(err, returnedDB) {
    if (err) {
	throw err;
    }

    db = returnedDB;
    
    formsCollection = db.collection('forms');
}


mc.connect('mongodb://localhost/examforms', connectCallback);


app.get('/', function(req, res, next) {
  res.render('index', { title: 'COMP 2406 Exam form demo' });
});

app.post('/add', function(req, res) {
    var obj = { name: req.body.name,
		city: req.body.city,
                country: req.body.country,
                birthday: req.body.birthday,
                email: req.body.email };
    state.push(obj);

    formsCollection.insert(obj, null);
    res.redirect('/list');
});

app.get('/list', function(req, res) {

    var findCallback = function(err, dbstate) {	
	if (err) {
	    console.log("Couldn't query database for some reason");
	    return;
	}
	res.render('list', { title: 'People Listing',  items: dbstate});
    }

    formsCollection.find({}).toArray(findCallback);
});

var serverUp = function() {
    console.log("ExamForms listening on port " + port);
}

var serverDown = function() {
    console.log("Server shutting down.");
    process.exit(0);
}

var server = http.createServer(app);
server.listen(port);
server.on('listening', serverUp);
process.on('SIGINT', serverDown);