mardi 31 mars 2015

NodeJS Variable Scope

I'm very, very new to the whole NodeJS stack, and I'm trying to rough up a simple login system for practice.


Jumping to my question,


app.js



...
var mongoose = require( 'mongoose' );
var templates = require( './data/inc.js' ); // includes schema structures
...




user.js - included in inc.js



...
module.exports =
{
"Schema" : new exports.mongoose.Schema({
"uid": mongoose.Schema.Types.ObjectId,
"username": { type:String, unique:true },
"alias": String,
"credentials":
{
"salt": String,
"password": String,
"key": String
},
"profile":
{
"age": { type: Number, min: 18 }
},
"last_login": Date,
"updated": { type: Date, default: Date.now }
})
}
...


The 'user.js' script above will not work because it doesn't have access to the mongoose object variable instantiated in the 'app.js' script. In PHP any included/required scripts would be able to access variables from the parent script, but in NodeJS as I know it for example I have to re-require/state the mongoose variable in order to create my schema tree.


user.js



...
* var mongoose = require( 'mongoose' ); // must include in script to use mongoose object

module.exports
{
...
}
...


Is there any work-around that will allow me the same scope access as PHP?


Aucun commentaire:

Enregistrer un commentaire