Consider a very simple Express 4 app structure:
-- app.js
-- models
|--db.js
|--news.js
where news.js
contains a mongoose schema and a model based on that schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var newsSchema = new Schema({
title: String,
subtitle: String,
// other fields...
});
var News = mongoose.model('News', newsSchema);
To my understanding, in order for app.js
to use the News
model, it has to require the file within the script like this: require('./models/news')
. Also, news.js
would have to export the model like this: module.exports = News;
.
However, I have come across a number of scripts that do not export models (or anything for that matter) defined in a separate file while still be able to use those models and/or schema in a different file just by requiring the model file and then do something like this:
var mongoose = require('mongoose');
var News = mongoose.model('News');
How is this behavior possible? It is a special feature of Mongoose? How can a file use a model or schema defined in another file if that model/schema is not exported within that file?