Home Ask Login Register

Developers Planet

Your answer is one click away!

Rob February 2016

export mongo database connection to models.js file

app.js file:

var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');

var conn = mongoose.createConnection('mongodb://localhost/database_name');

var app = express();
app.set('view engine','ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(express.static(path.join(__dirname, 'public')));


exports.conn = conn;

app.listen(3000,function(request, response){
    console.log("Server is running at Port 3000");

models.js file:

var mongoose = require('mongoose');
var app = require('./app');

var conn = app.conn

module.exports.User = conn.model('User', new mongoose.Schema({
    username: String,
    password: String,

On running node app.js, i am getting an error that TypeError: Cannot read property 'model' of undefined. app.js and models.js are in the same folder.

P.S. i am using createConnection function because i have to make two database connections.


Rob February 2016

finally figured it out:

to make it globally available we need to replace following line

var conn = mongoose.createConnection('mongodb://localhost/database_name');


module.exports.conn = mongoose.createConnection('mongodb://localhost/database_name');

migg February 2016

You should not require app.js inside a module. That defeats the purpose. Either use a separate module that handles the connection, or use dependency injection like this:


var mongoose = require('mongoose');

module.exports = function(conn) { // inject connection
    return {
        User: conn.model('User', new mongoose.Schema({
            username: String,
            password: String,


var conn = mongoose.createConnection('mongodb://localhost/database_name');

var models = require('./models')(conn);

models.User(...) // do stuff with User function

This is better structured, more maintainable and better testable as you can inject a mock for conn.

Post Status

Asked in February 2016
Viewed 2,620 times
Voted 12
Answered 2 times


Leave an answer

Quote of the day: live life