Global VARs

44 views
Skip to first unread message

Emerson Luiz

unread,
May 31, 2016, 9:40:56 AM5/31/16
to nodejs
HI,

I need get some info in my MongoDB and set the results as GLOBAL VARS in node.js.

Someone has done this before ?
Can show how you done this ?

Thanks

Aria Stewart

unread,
May 31, 2016, 10:26:44 AM5/31/16
to nod...@googlegroups.com
That probably isn't a thing you really want to do. It'd go something like this:

myMongoConnection.get('some key', function (err, data) {
if (err) throw new Error("I have no idea how to handle this error because of what we're doing here");
global.something = data.somethingelse;
})

But what task are you actually trying to do here? If one module is dependent on another, perhaps have it explicitly depend on it; if this is initialization step to get configuration that everything else needs, perhaps this belongs in a loader that makes a config object and passes it to the things that use it. If it _is_ a config loader, where is the db config coming from?

Knowing what you're trying to do at a higher level might help guide toward a better design.

Aria

Emerson Luiz

unread,
May 31, 2016, 10:50:09 AM5/31/16
to nodejs
Aria,

Thanks for your response...

I use MongooseJS, i think his no have method GET.

I need  take this variable  for all modules in my app.

Thanks again.

Aria Stewart

unread,
May 31, 2016, 11:06:38 AM5/31/16
to nod...@googlegroups.com

> On May 31, 2016, at 10:41, Emerson Luiz <elu...@gmail.com> wrote:
>
> Aria,
>
> Thanks for your response...
>
> I use MongooseJS, i think his no have method GET.
>
> I need take this variable for all modules in my app.

with mongoose, you'd use `yourModel.find`, since it's an object mapper, not just a plain mongo client. It's got schemas and such that you'd want to use.

It may be useful to you to use some simple injection in your app: instead of modules like so:

module.exports = function thing() {
global.config // used here
}

you may want to do this:

module.exports = function mymodule(config) {
return function thing() {
config // used here
}
}

So your configuration bit can load the rest of your app. Maybe not, but global variables are a smell and it's worth thinking about the order things load in and how easy it is to mess that up.

Reply all
Reply to author
Forward
0 new messages