How to reference Mongoose db from external models?

I'm working with the Nodepad tutorial on DailyJS. I've forked it and am extending it to work for my own purposes. One issue I have with it is that the whole application is written in the app.js file, and I prefer to separate my application a bit more. How should I write mongo into my seperate Model files since everything mongoose related is in app.js.

What do I need to bring over to my external files so that they can properly connect to the database and understand my mongoose schemas?

Here is an example pulled directly from Gitpilot:

user.js:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId; //not needed here, but may be needed in another model file

UserSchema = new Schema({
    email: {type: String, "default": ''},
    created_at: {type: Date, Date.now}
});

User = mongoose.model('users', UserSchema); //name of collection is 'users'

module.exports.User = User;
module.exports.Schema = UserSchema;

Then in your other file...

var mongoose = require('mongoose')
  , User = require('./user').User;

mongoose.connection.once('open', function() {
  var u = new User({email: 'youremail@something.com'});
  u.save();
});
mongoose.connect(); //default connect to localhost, 27017

Note: Some fields were removed from the User model for the sake of brevity. Hope this helps.

The neatest way to do this is to register the models with Mongoose on app init as you've done, then when you want to work with them, simply retrieve them from Mongoose, rather than requiring 'user' again.

You can also make things easier by opening the default connection with Mongoose, unless you have specific requirements that mean you have to manually manage each connection.

Do it like this:

app.js

var mongoose = require('mongoose');
require('./models/user');
mongoose.connect('server', 'database');

models/user.js

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

UserSchema = new Schema({
    email: {type: String, "default": ''},
    created_at: {type: Date, Date.now}
});

mongoose.model('User', UserSchema); // no need to export the model

anywhere else...

var mongoose = require('mongoose')
  , User = mongoose.model('User');

var u = new User({email: 'youremail@something.com'});
u.save();