1

I've created an extremely simple Node.js app based on Express's route-separation example. I want to power this app with the MongoDB driver Mongoose. This example just lists Users and Kittens.

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var user = require('./user');
var kitten = require('./kitten');

// Connect MongoDB
mongoose.connect('mongodb://localhost/mongoose');

// Express config here
...

// User
app.all('/users', user.list);

// Kitten
app.all('/kittens', kitten.list);

// Mongoose connection
var db = mongoose.connection;
db.once('open', function callback () {
  var kittySchema = mongoose.Schema({ name: String });
});

if (!module.parent) {
  app.listen(3000);
  console.log('Express started on port 3000');
}

To me it seems it would be wise to connect to the Mongo database on startup rather than for each request.

But how do I share that Mongoose connection with both the user and kitten routes? I know if I didn't need to share the connection between the two, I could just connect to the database in my user.js and kitten.js code.

Cory Klein
  • 51,188
  • 43
  • 183
  • 243

1 Answers1

2

In node.js when you do require a file, you run the code in that file exactly once. Which means you can store things through closure.

foobardb.js

(function(){
  "use strict"; // always nice to have

  var mongoose = require('mongoose'),
      databaseConnection; 

  module.exports = function() {

      if ( !databaseConnection ) {
           mongoose.connect('mongodb://localhost/mongoose')
           databaseConnection = mongoose.connection;
      }

      (...)
  };

})();

The databaseConnection will be shared with all the require("foobardb.js"); you do

fmsf
  • 36,317
  • 49
  • 147
  • 195