Whesley Barnard
Whesley Barnard

Reputation: 309

mean.js uses require without var

Have a question with regards to the default meanjs app from yeoman.

Inside the express.js file it has a statement like so:

// Globbing model files
config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
    require(path.resolve(modelPath));
});

Now I understand that it gets all the .js files inside the path "./app/models/", but what I am trying to understand is the alone standing

require(path.resolve(modelPath));

How is the require function being used without it being set to a "var"?

An example of one of these included files is like this:

'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/**
 * Article Schema
 */
var ArticleSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    title: {
        type: String,
        default: '',
        trim: true,
        required: 'Title cannot be blank'
    },

    content: {
        type: String,
        default: '',
        trim: true
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});

mongoose.model('Article', ArticleSchema);

This file doesn't expose anything.

So why is the require being called with a "var" and without the contents exposing a function?

How will this allow for the contents to be used later?

Upvotes: 0

Views: 183

Answers (1)

tkounenis
tkounenis

Reputation: 630

The code in the express.js file executes the contents of your model files. The anatomy of a MEAN.js model file is the following;

  1. Load the mongoose and schema packages, along with all your included models (if any).

  2. Declare the schema for the given model

  3. Register the given schema under the model name (Article for the given example).

There is nothing to return, hence the lack of any variable assignment in the express.js file. From now on you can call models by the label you assigned in the third part. Therefore, in your controller, you would write something like;

var articles = Article.query();

This line of code would load up the Article schema and run the provided query() method in your back-end (which by default returns all the instances in the database under that model).

In general, remember; not all functions return something.

Upvotes: 1

Related Questions