Alexander Tarasenko
Alexander Tarasenko

Reputation: 912

Export db object in node js

I really can't understand. let's say I have conneced to my mongodb

let db;
app.use(bodyParser.json());
app.use('/api/todos', todosRoutes); // routes in separate file

MongoClient.connect(
  uri, 
  {useNewUrlParser: true}, 
  (err, client) => {
    if(err) {
      return console.log(err)
    }
    db = client.db('todosApp');
    module.exports = db; // how can I export this db so my routes can use it?
    app.listen(PORT, () => {
      console.log(`app is listening on port ${PORT}`);
    })
  }
)

In my routes

const db = require('../app').db;
const collectionName = 'todos';

router.get('/', (req, res) => {
  db.collection(collectionName)
    .find()
    .toArray()
    .then(collection => res.json(collection))
    .catch(err => res.status(500).json(err))
})

I always get an error that db is undefined, which I can understand, but can't get how to handle it then?

Upvotes: 0

Views: 226

Answers (1)

SLaks
SLaks

Reputation: 887767

You require()d that file and got the value of require('../app').db synchronously, before app set exports.db.

You should only access .db later, once it actually exists.

Upvotes: 1

Related Questions