niktehpui
niktehpui

Reputation: 556

Generic requiring in node.js

I am currently working on a small personal multiplayer game project. I am using node.js along with express.js, mongoose and socket.io. It is my first project with JavaScript, I come from a C/C++ background.

The question is: Whether some kind of generic requiring is possible: I have currently a models folder in my project root and all the mongoose models are in there, they all look similar to this one:

function make(Schema, mongoose) {
var UserSchema = new Schema({
    name      : String
  , passwd    : String
  , is_online : Boolean
  , socket_id : Number
});
mongoose.model('User', UserSchema);
}
module.exports.make = make;

If I remember right, I found this approach somewhere on stackoverflow. Now when I am starting the node.js application, I have to connect to the database and then have to call all the make functions.

Is there a generic way to do that?

Somethink like this (pseudo-code):

models = require('./models/');
for each m in models do
{
     m.make(Schema, mongoose);
}

Upvotes: 0

Views: 265

Answers (1)

Jonas Osburg
Jonas Osburg

Reputation: 1783

I do it a little different:

var UserSchema = new Schema({
    name      : String
  , passwd    : String
  , is_online : Boolean
  , socket_id : Number
});
module.exports = mongoose.model('User', UserSchema);

Now I can require the model and use it right away like this:

var userModel = require('models/user');
userModel.find()//...

Upvotes: 1

Related Questions