Skip to content

Instantly share code, notes, and snippets.

@torchhound
Created November 1, 2018 01:08
Show Gist options
  • Save torchhound/ef03daee4d82e3ab533cee97be024f03 to your computer and use it in GitHub Desktop.
Save torchhound/ef03daee4d82e3ab533cee97be024f03 to your computer and use it in GitHub Desktop.
mongo-crud index.js
const express = require('express')
const bodyParser = require('body-parser')
const MongoClient = require('mongodb').MongoClient
const dbName = process.env.NODE_ENV === 'dev' ? 'database-test' : 'database'
const url = `mongodb://${process.env.MONGO_INITDB_ROOT_USERNAME}:${process.env.MONGO_INITDB_ROOT_PASSWORD}@${dbName}:27017?authMechanism=SCRAM-SHA-1&authSource=admin`
const options = {
useNewUrlParser: true,
reconnectTries: 60,
reconnectInterval: 1000
}
const routes = require('./routes/routes.js')
const port = process.env.PORT || 80
const app = express()
const http = require('http').Server(app)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/api', routes)
app.use((req, res) => {
res.status(404)
})
MongoClient.connect(url, options, (err, database) => {
if (err) {
console.log(`FATAL MONGODB CONNECTION ERROR: ${err}:${err.stack}`)
process.exit(1)
}
app.locals.db = database.db('api')
http.listen(port, () => {
console.log("Listening on port " + port)
app.emit('APP_STARTED')
})
})
module.exports = app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment