Aren Li
Aren Li

Reputation: 1962

How to use a mongoose model defined in a separate file if the file is not exported?

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?

Upvotes: 9

Views: 8033

Answers (1)

robertklep
robertklep

Reputation: 203231

This ultimately works because when you call require('mongoose') in various files, you get back the same object. In other words: it gets shared between app.js and news.js, in your case.

When you create a new model (using mongoose.Model('Name', schema)), Mongoose stores that model instance in an internal list of models.

This also allows you to get an instance by name, using mongoose.Model('Name'). Mongoose will look up that model in its internal list, and return it.

Upvotes: 7

Related Questions