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.
connyou are requiring in themodels.js? Do you try to use the variableconnfrom theapp.jslike this? This is not how node.js works.require('conn')will look intonode_modulesfor a package namedconn.