You could use it this way:
that's server.js file:
import path from 'path'
import express from 'express'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import db from './server/database'
import routes from './server/routes'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import webpackConfig from './config/webpack'
const app = express()
const port = process.env.PORT || process.env.NODE_PORT
const compiler = webpack(webpackConfig)
db(λ => {
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }))
app.use(webpackHotMiddleware(compiler))
app.use(morgan('dev'))
app.use(bodyParser.json({ limit: '20mb' }))
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }))
app.use('/static', express.static('static'));
//app.use('/api', jwt)
app.use('/api', routes())
app.set('json spaces', 2)
app.get('*', function(request, response) {
response.sendFile(path.resolve(__dirname, 'index.html'))
})
app.listen(port, (error) => {
if (error) {
console.error(error)
throw error
} else {
console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`)
}
})
})
server/database.js
import mongoose from 'mongoose'
export default callback => {
const { MONGO_URL, MONGO_PORT, MONGO_DB } = process.env
mongoose.connect(`mongodb://${MONGO_URL}:${MONGO_PORT}/${MONGO_DB}`, error => {
if (error) {
console.error('Please make sure your MongoDB configuration is correct and that service is running')
throw error
}
})
callback()
}
Then you'll have to define your mongoose models, for instance:
import mongoose, { Schema } from 'mongoose'
const ideaSchema = new Schema({
title: {
type: String,
required: true
},
slug: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true
}
})
export default mongoose.model('Idea', ideaSchema)
And just use controllers this way:
import HttpStatus from 'http-status-codes'
import mongoose from 'mongoose'
import sanitize from 'sanitize-html'
import slug from 'slug'
import Idea from '../models/idea'
const findAllIdeas = (req, res) => {
Idea.find()
.select('user title slug createdAt updatedAt')
.populate({
path: 'user',
select: 'firstName lastName'
})
.then(data => res.status(HttpStatus.OK).json(data))
.catch(error => res.status(HttpStatus.BAD_REQUEST).json(error))
}
export default { findAllIdeas, findIdeaBySlug, createIdea, addComment }
You will not have to connect to mongoDB for each get request.
So your route will look like that. Quite straightforward:
import { Router } from 'express'
import controller from '../controllers/idea'
const router = Router()
router.route('/')
.get(controller.findAllIdeas)
.post(controller.createIdea)
router.route('/:slug')
.get(controller.findIdeaBySlug)
router.route('/comment')
.post(controller.addComment)
export default router