NodeJS MongoDB Tutorial

NodeJS MongoDB TutorialIn this video I show the easiest way to connect NodeJS to a MongoDB database. Installation and solving common errors is covered. We’ll create a database and then query and update it using NodeJS. We’ll review how to template pages with Jade. We review how to set up a NodeJS tutorial. Also because of requests, I will show myself writing all of the code.

I have other tutorials on the following topics if you want to learn more about : NodeJS, MongoDB, or Jade. All of the code follows the video below.

If you like videos like this, it would help me greatly if you’d support me on Patreon.

After making just $3.49 off of my last 8 videos I decided if I want to keep making educational videos I’ll have to look for an income source. $1 is greatly appreciated! If you can’t afford it though that is perfectly ok because I’m very happy that my videos are helping over 30 million people each month.

[googleplusone]

Code From the Video

package.json

{
  "name": "sampsite",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "kerberos": "~0.0.17",
    "mongodb": "~2.0.33",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0"
  }
}

app.js

// Imports all the modules needed
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');

// Used to connect to the MongoDB database
var mongo = require('mongodb')

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// Define the directory with the views and to use Jade
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

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

// Define what route files to use being routes/index.js for /
// routes/users.js for /users
// The route files then render the page
app.use('/', routes);
app.use('/users', users);

// 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;

index.js

var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');

/* GET home page. */
// Defines the root route. router.get receives a path and a function
// The req object represents the HTTP request and contains
// the query string, parameters, body, header
// The res object is the response Express sends when it receives
// a request
// render says to use the views/index.jade file for the layout
// and to set the value for title to 'Express'
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/thelist', function(req, res){

  // Get a Mongo client to work with the Mongo server
  var MongoClient = mongodb.MongoClient;

  // Define where the MongoDB server is
  var url = 'mongodb://localhost:27017/sampsite';

  // Connect to the server
  MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the Server', err);
  } else {
    // We are connected
    console.log('Connection established to', url);

    // Get the documents collection
    var collection = db.collection('students');

    // Find all students
    collection.find({}).toArray(function (err, result) {
      if (err) {
        res.send(err);
      } else if (result.length) {
        res.render('studentlist',{

          // Pass the returned database documents to Jade
          "studentlist" : result
        });
      } else {
        res.send('No documents found');
      }
      //Close connection
      db.close();
    });
  }
  });
});

// Route to the page we can add students from using newstudent.jade
router.get('/newstudent', function(req, res){
    res.render('newstudent', {title: 'Add Student' });
});

router.post('/addstudent', function(req, res){

    // Get a Mongo client to work with the Mongo server
    var MongoClient = mongodb.MongoClient;

    // Define where the MongoDB server is
    var url = 'mongodb://localhost:27017/sampsite';

    // Connect to the server
    MongoClient.connect(url, function(err, db){
      if (err) {
        console.log('Unable to connect to the Server:', err);
      } else {
        console.log('Connected to Server');

        // Get the documents collection
        var collection = db.collection('students');

        // Get the student data passed from the form
        var student1 = {student: req.body.student, street: req.body.street,
          city: req.body.city, state: req.body.state, sex: req.body.sex,
          gpa: req.body.gpa};

        // Insert the student data into the database
        collection.insert([student1], function (err, result){
          if (err) {
            console.log(err);
          } else {

            // Redirect to the updated student list
            res.redirect("thelist");
          }

          // Close the database
          db.close();
        });

      }
    });

  });

module.exports = router;

newstudent.jade

extends layout

block content
  h3= title
  form#form_add_student(name="addstudent", method="post", action="/addstudent")
    span Name
    span  
    input#input_name(type="text", placeholder="student", name="student")
    br
    br
    span Street
    span  
    input#input_street(type="text", placeholder="street", name="street")
    br
    br
    span City
    span  
    input#input_city(type="text", placeholder="city", name="city")
    br
    br
    span State
    span  
    input#input_state(type="text", placeholder="state", name="state")
    br
    br
    span Sex
    span  
    input#input_sex(type="text", placeholder="sex", name="sex")
    br
    br
    span GPA
    span  
    input#input_gpa(type="text", placeholder="gpa", name="gpa")
    br
    br
    button#submit_student(type="submit") submit

studentlist.jade

extends layout

block content
  h3.
    Students
  ul
    each student, i in studentlist
      li#student_list_item
        a(href='#') #{student.student} lives at #{student.street} #{student.city}, #{student.state}

Leave a Reply

Your email address will not be published. Required fields are marked *