The models index file

There's one last file in the models folder that we haven't yet touched on in our project. The index.js file within any folder in Node.js acts as an index file for the modules within it. This is by convention, so you don't have to adhere to this if you don't want to.

Since our models folder will contain a number of different files, each a unique module for one of our models, it would be nice if we could just include all of our models in a single require statement. Using the index.js file, we can do so pretty easily too. Copy the following block of code into the models/index.js file:

module.exports = { 
    'Image': require('./image'), 
    'Comment': require('./comment') 
};

The index.js file inside the models directory simply defines a JavaScript object that consists of a name-value pair for each module in our directory. We manually maintain this object, but this is the simplest implementation of the concept. Now, thanks to this basic file, we can perform require('./models') anywhere in our application and know that we have a dictionary of each of our models via that module. To reference a specific model in that module, we simply refer to the specific model as a property of the module. If we only wanted to require a specific model somewhere in our app instead, we could perform require('./models/image') just as easily! You will see more of this a little later, and it will become much clearer.

Because our two models are so closely related, we are typically always going to require the models dictionary using require('./models') throughout our application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.11.247