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.