Skip to content

Instantly share code, notes, and snippets.

@senthilmpro
Created November 27, 2018 22:34
Show Gist options
  • Save senthilmpro/86e0c381b3f66821856d5c41948b2bca to your computer and use it in GitHub Desktop.
Save senthilmpro/86e0c381b3f66821856d5c41948b2bca to your computer and use it in GitHub Desktop.
Node.js MongoDB connect
var db = null // global variable to hold the connection
MongoClient.connect('mongodb://localhost:27017/', function(err, client) {
if(err) { console.error(err) }
db = client.db('test') // once connected, assign the connection to the global variable
})
app.get('/', function(req, res) {
db.collection('test').find({}).toArray(function(err, docs) {
if(err) { console.error(err) }
res.send(JSON.stringify(docs))
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment