Created
November 27, 2018 22:34
-
-
Save senthilmpro/86e0c381b3f66821856d5c41948b2bca to your computer and use it in GitHub Desktop.
Node.js MongoDB connect
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 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