Last active
February 21, 2017 14:00
-
-
Save chrisckchang/eae2a35ae056734b2c89 to your computer and use it in GitHub Desktop.
Contact list app initialization and database connection
This file contains hidden or 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 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 ***************************************** |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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??