Skip to content

Instantly share code, notes, and snippets.

@sivasankars
Created July 8, 2018 04:26
Show Gist options
  • Save sivasankars/f81e89040995f3713cf91bbbdec5661a to your computer and use it in GitHub Desktop.
Save sivasankars/f81e89040995f3713cf91bbbdec5661a to your computer and use it in GitHub Desktop.
Best Practice of Connecting MongoDB Using Mongoose ODM
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