Skip to content

Instantly share code, notes, and snippets.

@chrisckchang
Last active February 21, 2017 14:00
Show Gist options
  • Save chrisckchang/eae2a35ae056734b2c89 to your computer and use it in GitHub Desktop.
Save chrisckchang/eae2a35ae056734b2c89 to your computer and use it in GitHub Desktop.
Contact list app initialization and database connection
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var ObjectID = mongodb.ObjectID;
var CONTACTS_COLLECTION = "contacts";
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
// Create a database variable outside of the database connection callback to reuse the connection pool in your app.
var db;
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(process.env.MONGOLAB_URI, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
// ***************************************** CONTACTS API ROUTES *****************************************
@amer1616
Copy link

Great Thanks.
I'm curious to know if you want to separate api routes in different file, e.g. api.js. how can you reuse db in that api.js??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment