Cristian G
Cristian G

Reputation: 799

As I can put global variables in the controllers?

I need something like the following:

module.exports = {

    'globalVariable' : "globalVariable"  ,

    'index' : function(req, res, next){

        this.proyectos = "";

        Proyecto.find().done(function(err, proyectos){
            globalVariable = proyectos;
        });

        res.view({
           'data' : globalVariable
        });   
    },

  _config: {}
};

This will help me so much to avoid making requests to the database and could send data from different models to the view.

Thank you very much for the help you can give me.

Upvotes: 1

Views: 704

Answers (1)

sgress454
sgress454

Reputation: 24948

You can just declare the variable outside of the module.exports block:

var globalVariable = "globalVariable";

module.exports = {

    'index' : function(req, res, next){

        this.proyectos = "";

        Proyecto.find().done(function(err, proyectos){
            globalVariable = proyectos;
        });

        res.view({
           'data' : globalVariable
        });   
    },

  _config: {}
};

Note that this is not "global" across the entire app; it's restricted to the scope of the controller it's declared in.

Upvotes: 2

Related Questions