I'm new to node and I've a remote database hosted on mlab and I want to connect to my database using mongoose.connect
. I want to access that database to a specified route.
My code looks like :
var db = null;
db = mongoose.connect('mongodb://username:password@ds135186.mlab.com:12345/collection', function (err, database) {
db = database
});
and I've defined route as :
app.get('/fetchtest', function (req, res) {
db.collection('okhitweets').find({}).limit(10).toArray(function (err, doc) {
res.send(JSON.stringify(doc))
})
});
I'm getting can't find collection of undefined
because db is not getting initialised. I tried finding online about how to access database but couldn't get much help. How can I access this database. My application is gonna be fairly small so I don't need to define routes in different file etc. and the database exists on mlab cloud.