Daniel Daniel - 1 year ago 137
Javascript Question

Exporting a mongoose database module

I need to export my mongoose database module, so I could use my defined models from every module in my program.

For example, my database.js module looks something like that:

var mongoose = require('mongoose'),
db = mongoose.createConnection('mongodb://localhost/newdb'),
Schema = mongoose.Schema;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("Connected to database newdb");

var dynamicUserItemSchema = new mongoose.Schema({
userID: Number,
rank: Number,

var staticUserItemSchema = new mongoose.Schema({
_id: Schema.Types.Mixed,
type: Schema.Types.Mixed,

var DynamicUserItem = db.model('DynamicUserItem', dynamicUserItemSchema);
var StaticUserItem = db.model('StaticUserItem', staticUserItemSchema);


I want to be able adding
var db = require('../my_modules/database');
to any other module my program - so I will be able to use the models like that:

item = new db.DynamicUserItem({});

Is it possible doing that using "exports" or "module exports" ? Thanks.

Answer Source

I usually don't use the error and open events and follow the example from mongoosejs to create a connection to my db. Using the example you could do the following.


var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'test');

var schema = mongoose.Schema({ name: 'string' });
var Cat = db.model('Cat', schema);

module.exports = Cat; // this is what you want

and then in your app.js you can do something like

var Cat = require('db');

var peter = new Cat();

Hope that helps!