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')));
app.use(bodyparser.urlencoded({extended:true}));

app.use(require('./routes/index'));
app.use(require('./routes/page1'));
app.use(require('./routes/page2'));
app.use(require('./routes/page3'));
app.use(require('./routes/page4'));

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.

Answers


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');

with

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:

models.js

var mongoose = require('mongoose');

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

app.js

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

Search




Leave an answer