javascript - 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 running @ 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
, getting error typeerror: cannot read property 'model' of undefined
. app.js , models.js in same folder.
p.s. using createconnection function because have make 2 database connections.
you should not require app.js
inside module. defeats purpose. either use separate module handles connection, or use dependency injection 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(...) // stuff user function
this better structured, more maintainable , better testable can inject mock conn
.
Comments
Post a Comment