Created
July 8, 2018 04:26
-
-
Save sivasankars/f81e89040995f3713cf91bbbdec5661a to your computer and use it in GitHub Desktop.
Best Practice of Connecting MongoDB Using Mongoose ODM
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
var mongoose = require('mongoose'); | |
var express = require('express'); | |
// Connect to MongoDB Using Mongoose ODM | |
mongoose.connect('mongodb://localhost:27017/integration_test', { useNewUrlParser: true }); | |
// Listen For Mongoose Connection Error | |
mongoose.connection.on("error", function (err) { console.error('Failed to Connect MongoDB'); }); | |
// Listen For Mongoose Disconnection | |
mongoose.connection.on('disconnected', function () { console.log('MongoDB Disconnected'); }); | |
// Listen For Mongoose Connection | |
mongoose.connection.on("connected", function () { | |
console.log("MongoDB Connected"); | |
// Express.js HTTP Server | |
var app = express(); | |
port = process.env.port || 3000; | |
ip = process.env.ip; | |
app.listen(port, ip, function () { | |
console.log('listening on port ' + port); | |
}); | |
}); | |
var onTerminate = function () { | |
mongoose.connection.close(function () { | |
console.log('Close MongoDB Connection'); | |
process.exit(0); | |
}); | |
} | |
// Fire the Event On Application Stop/Termination | |
process.on('SIGINT', onTerminate).on('SIGTERM', onTerminate); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment