Challenge 4 - Mongoose

In notebook:
FrontEndMasters Building Web Apps with Node.js
Created at:
pattern backend Node JS JavaScript libraries
Video Course on Building Web Applications with Node.js

Use Mongoose to save and retreive blog articles

  1. start up mongodb (locally) 
  2. create a nodejs module for mongoose
  3. connect to mongodb, set up schema, and model, export
  4. create a route to list all items with find
  5. create a POST route, create a new item and save it
Start up mongodb locally:
​mongod --dbpath=/Users/bfulop/work/__mongodata --port 27017​  
NodeJS mongoose module to interact with the DB:
  // Post.js

// Require mongoose
var mongoose = require('mongoose');

// Configure conenction URL (only needs to happen once per app)

// Create a database schema for our Post object, which will describe both it's
// data and it's behavior.
var postSchema = mongoose.Schema({

// Create a model object constructor that will have ODM functionality like .save()...
var Post = mongoose.model('Post', postSchema);

// Expose out model as the module interface
module.exports = Post;
Use this module in app.js:
​var Post = require('./Post');
list all items with find:
  // Render our home page with all blog posts
app.get('/', function(request, response) {
    Post.find(function(err, posts) {
        if (err) {
            response.send(500, 'There was an error - tough luck.');
        else {
            response.render('index', {
Create a post route, create a new item and save it. Get the post data from the ​request.body​ object:
  // create a new blog post object'/create', function(request, response) {
    //Create and save a Post model
    var post = new Post({
        title: request.body.title,
        content: request.body.content

    //Save the model, model) {
        if (err) {
            response.send(500, 'There was an error - tough luck.');
        else {
the HTML for the form to POST:
  <form action="/create" method="POST">
    <label>Post Title</label>
    <input type="text" name="title" placeholder="Type a title..."/>

    <label>Post Content</label>
    <textarea name="content" rows="5"></textarea>
        <button type="submit" class="btn">Submit</button>
explains package.json file, most notable the ​dependencies​ section 

​to pull down all the dependencies: ​$npm install​  

a shortcut if you experiment with something to add to package.json :

​npm install twilio --save​ its will add an entry to the package.json file

Use authentication

basic authentication, middleware
  var auth = express.basicAuth(function(username, password){
    return username === "foo" && password === "bar";
Then just add the ​auth​ middleware we created to our routes:'/create', auth, function(request, response) {...​  

or if you want to apply it to every route:


Create an API for listing blog posts as JSON

just use ​response.send({///...}​ instead of ​response.render​ 

the ​send​ will automatically serialise to json:
  app.get('/posts.json', function(request, response) {
    Post.find(function(err, posts) {
        if (err) {
            response.send(500, {
                success: false
        else {
                success: true,
                posts: posts