Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fahmifan
Created May 2, 2019 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fahmifan/3e20b274b5860499ab8ca62dfde91d85 to your computer and use it in GitHub Desktop.
Save fahmifan/3e20b274b5860499ab8ca62dfde91d85 to your computer and use it in GitHub Desktop.
Mongodb connection nodejs
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