Created
May 2, 2019 03:44
-
-
Save fahmifan/3e20b274b5860499ab8ca62dfde91d85 to your computer and use it in GitHub Desktop.
Mongodb connection nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const path = require('path'); | |
const mongoose = require('mongoose'); | |
const router = require('./routes'); | |
const bodyParser = require('body-parser'); | |
const { loggerMiddleware } = require('./logger') | |
const app = express(); | |
const config = { | |
PORT: process.env.PORT || '8080', | |
ENV: process.env.NODE_ENV || 'development', | |
DB_URL: process.env.DB_URL || 'mongodb://localhost/ppl-tilda', | |
} | |
// connect to db | |
mongoose.connect(config.DB_URL, {useNewUrlParser: true}); | |
const db = mongoose.connection; | |
db.on('error', console.error.bind(console, 'connection error:')); | |
db.once('open', () => { | |
console.log('connect to mongodb'); | |
const userSchema = new mongoose.Schema({ | |
name: String, | |
email: String, | |
pictURL: String, | |
telp: String, | |
progress: Array, | |
callHistory: Array, | |
}); | |
const UserModel = mongoose.model('User', userSchema); | |
// parse application/x-www-form-urlencoded | |
app.use(bodyParser.urlencoded({ extended: false })); | |
// parse application/json | |
app.use(bodyParser.json()); | |
app.use(loggerMiddleware()); | |
app.use('/', express.static(path.join(__dirname, '../frontend'))); | |
app.get('/api/ping', (req, res) => res.status(200).json({ message: 'pong' })); | |
app.use('/api', router({ UserModel })); | |
app.listen(config.PORT, () => { | |
console.log(`starting ${config.ENV} server at http://localhost:${config.PORT}`); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment