1

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.

Ajay Gaur
  • 5,140
  • 6
  • 38
  • 60
  • The answer to the *can't find collection of undefined* is [here](https://stackoverflow.com/a/47662979/8574934). However, when you are using Mongoose you're usually not accessing the collections like that. – Mika Sundland Dec 09 '17 at 10:27

1 Answers1

4

You can add following to server.js (i.e. main file) right after your database assignment (not in the scope where you assign, but after in a global one).

app.use( (req, res) => {
    req.db = db
})

And then in your routes (or in main file) say

app.get("/chocolate", (req, res) => {
    const db = req.db
    db.collection("chocolates").find({})
         .toArray()
         .then(results => {
              res.status(200).send(results)
          })
})

And you can also check the EventEmitter out, so that you start server only if you connect to the DB.

Let me know if this helps.

EDIT 1: If you are still "alive" (just joking), the snippet below may be more applicable than the one I share

app.all('*', (req, res, next) => {
    req.db = db;
    next();
});

This also makes the db connection available throughout all routes.

oneturkmen
  • 1,288
  • 1
  • 11
  • 27