Mongo Express * Node

ES6
MIT Licensed
No public assets
EJS views
We used: Airbnb style guide

package.json

Set up package.json to include:

"dependencies": {
    "mongoose": "^4.5.5",
    "express": "^4.14.0",
    .
    .
    .
  },


server.js

Mongoose MongoDB connection
The main node server script:

const express = require('express'),
    path = require('path'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    home = require('./server/controllers/home'),
    restApi = require('./server/controllers/restApi'),
    app = express(),
    mongoose = require('mongoose');

// Test DB Data
const db = 'mongodb://me_n:me_n@ds029735.mlab.com:29735/me_n';
mongoose.connect(db);

const monCon = mongoose.connection;
monCon.on('error', console.error.bind(console, 'connection error:'))
    .once('open', () => {
        console.log(`Mongo DB connected at ${db}`);
    });

app.set('views', path.join(__dirname, 'views'))
    .set('view engine', 'ejs')
    .use(favicon(path.join(__dirname, 'views', 'favicon.ico')))
    .use(logger('dev'))
    .use(bodyParser.json())
    .use(bodyParser.urlencoded({extended: false}))
    .use(cookieParser())
    .use('/', home)
    .use('/restApi', restApi);

const listener = app.listen(8888, () =>
    console.log(`Listening on port ${listener.address().port}`));

module.exports = app;


restApi.js

Support CRUD operations
Set up your controller:

const service = require('../services/service.js'),
    express = require('express'),
    restApi = express.Router();

restApi
    .get('/:id', (req, res) => service.fetch(req, res))
    .get('/', (req, res) => service.fetchAll(req, res))
    .post('/', (req, res) => service.post(req, res))
    .delete('/:id', (req, res) => service.remove(req, res))
    .put('/:id', (req, res) => service.put(req, res));

module.exports = restApi;


service.js

Separation of concerns - business logic into service:

const ExampleModel = require('../models/example'),
    mongoose = require('mongoose');

module.exports = {
    put(req, res) {
        ExampleModel.findByIdAndUpdate(req.params.id, { $set: req.body }, (err, result) => {
            if (err) {
                return res.send(err);
            }
            return res.json({ message: `${req.params.id} ${result}` });
        });
    },

    post(req, res) {
        const Example = new ExampleModel({
            _id: new mongoose.Types.ObjectId,
            content: req.body.content
        });

        Example.save((err) => {
            if (err) {
                return res.send(err);
            }
            return res.json({ message: `${req.body.content} successfully saved!` });
        });
    },

    remove(req, res) {
        ExampleModel.findById(req.params.id, (err, example) => {
            if (err) {
                return res.send(err);
            }
            return example.remove((error) => {
                if (error) {
                    return res.send(error);
                }
                return res.json({ message: `${req.params.id} successfully deleted!` });
            });
        });
    },

    fetch(req, res) {
        ExampleModel.findById(req.params.id, (err, example) => {
            if (err) {
                return res.send(err);
            }
            return res.json(example);
        });
    },

    fetchAll(req, res) {
        ExampleModel.find({}, (err, examples) => {
            if (err) {
                return res.send(err);
            }
            return res.json(examples);
        });
    }
};


example.js

Example model:

const mongoose = require('mongoose'),
    Schema = mongoose.Schema;

const exampleSchema = new Schema({
  _id: { unique: true, type: Schema.Types.ObjectId,
    default: new mongoose.Types.ObjectId, required: true },
  content: { type: String, required: true }
});

const Example = mongoose.model('exampleSchema', exampleSchema);

module.exports = Example;


Git it here: repo