Today I’ll be demonstrating how to use MongoDB and NodeJS together.


Requirements:

1. Create your package.json

click enter for all options that appear

$ npm init

you should now have a package.json file

2. Create your main index.js file

this file is the backbone of the entire application

$ touch index.js

Windows users create it manually.

3. Install the modules we’ll be using

  • express (webdev framework)
  • ejs (templating)
  • mongoose (connects express to mongodb)
$ npm install express ejs mongoose --save



4. Open up index.js and write this code. I’ll explain each line.

// index.js
var express = require("express");
var app = express();
var router = require("./router/router.js");

app.set("view engine", "ejs");
app.set("views", "./views");

app.use("/", router);

app.listen(3000);

// Pull in express and assign it to app.
var express = require("express");
var app = express();
// A router is the same as the app variable above.
// But it allows less code inside index.js
var router = require("./router/router.js");
// Add our template engine.
app.set("view engine", "ejs");
// Tell express where to find our rendered templates
app.set("views", "./views");
// Our router will handle all request made to /
app.use("/", router);
// Have our app listen on port 3000
app.listen(3000);



5. Create our router and views

cd into router and place an empty router.js file


$ mkdir router
$ cd router
$ touch router.js

cd into views and place an empty index.ejs file


$ mkdir views
$ cd views
$ touch index.ejs



6. Now we create a model

What’s a model? It’s the schema of the database.


$ mkdir models
$ cd models
$ touch names.js

and insert the following into names.js

// models/names.js
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/Names");

var Schema = mongoose.Schema({
  name: String
});

var Model = mongoose.model("Names", Schema);

module.exports = Model;
// Require monoose
var mongoose = require("mongoose");
// Tell mongoose where MongoDB is listening
mongoose.connect("mongodb://localhost/Names");
// A Schema defines the layout of a database.
// In this case only one column named name.
var Schema = mongoose.Schema({
  name: String
});
// This variable allows us to manipulate the database.
// First parameter is the name of the database and the second our Schema
var Model = mongoose.model("Names", Schema);
//module.exports lets us call Model from other parts of our app
module.exports = Model;



7. Open up router/router.js and let it handle manipulating the database. As well as handling http requests.

var express = require("express");
var Names = require("../models/names.js");

router.get("/", function(req, res){
  Names.find({}, function(err, names){
    if(err) throw err;
    if(names.length > 1){
      res.render("index", {data: names})
    } else{
      res.render("index", {data: "No names added yet!"})
    }
  });
});

router.get("/:name", function(req, res){
  var newName = new Names({ name: req.params.name });
  newName.save(function(err){
    if(err) throw err;
    res.redirect("/");
  });
});

module.exports = router;

router.get(“/”) pulls in all names from our database and hands the data to our index.ejs template

router.get(“/:name”) creates a new name in our database

8. Create our homepage inside views/index.ejs

<!DOCTYPE html>
<html>
<head>
  <title>MongoDB Web App</title>
</head>
<body>
<!-- Use EJS to print out our data-->
  
  <% for (var i = 0; i < data.length; i++) {%>
    <p> <%= data[i].name %> </p>
  <% } %>
  
</body>
</html>



9. Start up MongoDB

$ mongod



10. Start up your Node app

$ node index.js

MongoDB localhost

There should be nothing there if your database is empty. Start adding names by going to localhost:3000/YourNameGoesHere