I have a node app using Express and Mongoose. I have seen this line in demo app but I don't understand how it is working.
require('./db.js');
require('./routes.js')(app);
exports = mongoose = require('mongoose');
mongoose.connect('localhost:27017/test');
exports = Schema = mongoose.Schema;
require('./models.js')
var ArticleSchema = new Schema({
title : {type : String, default : '', trim : true}
, body : {type : String, default : '', trim : true}
, user : {type : Schema.ObjectId, ref : 'User'}
, created_at : {type : Date, default : Date.now}
})
mongoose.model('Article', ArticleSchema);
var Article = mongoose.model('Article');
module.exports = function(app){
app.get('/new', function(req, res){
var article = new Article({});
res.render('new', article);
});
};
How are the variables mongoose and schema available in the other modules like models.js and routes.js?
This code all still works if I change the exports = mongoose = require('mongoose');
line I saw in the demo to either of these which I am more familiar with.
module.exports = mongoose = require('mongoose');
exports.anything = mongoose = require('mongoose');
The variable name in the middle of the three assignments is what is available in other files.
Can someone explain what is going on here and how it is working?
Thanks!
Try this:
app.js
var db = require('./db.js');
require('./routes.js')(app, db);
db.js
var mongoose;
module.exports.mongoose = mongoose = require('mongoose');
mongoose.connect('localhost:27017/test');
module.exports.Schema = mongoose.Schema;
require('./models.js')(module.exports);
models.js
module.exports = function (db) {
var ArticleSchema = new db.Schema({
title : {type : String, default : '', trim : true}
, body : {type : String, default : '', trim : true}
, user : {type : db.Schema.ObjectId, ref : 'User'}
, created_at : {type : Date, default : Date.now}
})
db.mongoose.model('Article', ArticleSchema);
};
routes.js
module.exports = function (app, db) {
var Article = db.mongoose.model('Article');
app.get('/new', function(req, res){
var article = new Article({});
res.render('new', article);
});
};