Mongo node expressJs database connections

I'm using a mongoDB database with node / express and I want to know how could I make this more concise.

    app.get('/mediums', function(req, res){
        db.open(function(err, db) {
            db.collection('mediums').find().toArray(function(err, info){
                res.json(info)
                db.close();
            })
        });
    });
    app.get('/categories', function(req, res){
        db.open(function(err, db) {
            db.collection('categories').find().toArray(function(err, info){
                res.json(info)
                db.close();
            })
        });
    });
    app.get('/stock', function(req, res){
        db.open(function(err, db) {
            db.collection('stock').find().toArray(function(err, info){
                res.json(info)
                db.close();
            })
        });
    });

I want to write the db.open one time and then call it when I need it
something more like

database = db.open(function(err, db) {
    db.collection('stock').find().toArray(function(err, info){
        callback()
        db.close();
    })
});


app.get('/stock', function(req, res){
    database.collection('stocks').find().toArray(function(err, info ){
      res.json(info)
    })
});

I know this is not valid JS but something like this would be awesome!

Generally the mongoDB connection is kept open forever when the server is run. It is inefficient and cumbersome to open and close the connection every time. Just open the connection when you start the server and pass that variable wherever you need to query the database.

You can do something like this

db.open(function(err, db) {
   //start your express server here
   //use the db to query in the routes.
   //If you need the db in other files, you can use something like exports.db=db
   //in the case db isn't a singleton.

})

You can put your app initialization stuff inside the callback from db.open. Something like this:

db.open(function(err, db) {
    app.get('/mediums', function(req, res){
        db.collection('mediums').find().toArray(function(err, info){
            res.json(info);
        });
    });
    app.get('/categories', function(req, res){
        db.collection('categories').find().toArray(function(err, info){
            res.json(info);
        });
    });
    app.get('/stock', function(req, res){
        db.collection('stock').find().toArray(function(err, info){
            res.json(info);
        });
    });
});

You'll probably want your .listen call inside the db.open callback as well so that the app doesn't start listening before the db connection is open.