Nodejs undefined var when separate code in models
<p>I'm writting my first nodejs app, and i'm getting an error when i move a piece of code to an external js file. the code i'm trying to move is a mongodb schema declaration:</p>

<pre><code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//--------------------users ------------
var usersSchema = new Schema({
    email: String,
    name: String, 
    phoneNumber: String, 
    BirthDate: Date, 
    loginpwd:String
});

var UserModel = mongoose.model('users', usersSchema);
</code></pre>

<p>I'm using filesystem module to load the external file:</p>

<pre><code>fs.readdirSync(__dirname+'/models').forEach(function(filename){
    if (~filename.indexOf('.js')) 
        require(__dirname+'/models/'+ filename);
    console.log(filename+" added");
});
</code></pre>

<p>the following block does not work well when I separate the code, throwing an "undefined UserModel" error:</p>

<pre><code>var userData = new UserModel({email : req.body.edtEmail,
                                        name: req.body.edtName,
                                        phoneNumber: req.body.edtPhoneNumber,
                                        BirthDate: req.body.edtBirthDate,
                                        loginpwd: req.body.edtSenha});
// save user data to database
userData.save(function(err, record){
   if(err) throw err;

    // session setting
    req.session.userEmail = req.body.edtEmail;
    req.session.name = req.body.edtName;
    req.session.phoneNumber = req.body.edtPhoneNumber;
    req.session.birthDate = req.body.edtBirthDate;
    req.session.userId = record._id;
    res.redirect('/dashboard');
});
</code></pre>

<p>the following code works well in both inline code or "in file" code:</p>

<pre><code>app.get('/users/json', function(req, res){
    mongoose.model('users').find(function(err, users){
        res.send(users);
    });
 });
</code></pre>

<p>Am I doing something wrong when load external file ? or missing something ?</p>