Shamoon
Shamoon

Reputation: 43501

How do I properly lay out Mongoose in an Express project?

I created my Schema's in my models/mymodel.js file. I also have my models in there as well as my methods.

How do I export them into my routes?

Upvotes: 3

Views: 1021

Answers (2)

Jed Watson
Jed Watson

Reputation: 20378

Mongoose creates a singleton when you require() it, and subsequent calls return the same instance.

So as long as you require mongoose when your app inits, then define your models, they will be available in any other file where you require mongoose as described by Raynos.

Unless you want to manage connections to the db server manually, it's also a good idea to call mongoose.connect('...') in your app init; the connection will persist across requests.

Upvotes: 1

Raynos
Raynos

Reputation: 169391

// route.js
var mongoose = require("mongoose");

var Posts = mongoose.model("posts")
...

Ensure that you set up a bootstrap mechanism that runs all your model files. Once that is done you should have called mongoose.model("name", Model) for a set of models.

This has cached those models in mongoose internally. So you can just call mongoose.model("name") anywhere you want.

The only thing that's important is order of execution. The model & schemas need to be registered before you run your routes.

This is as a simple as :

// create app
var app = express.createServer(...);
// do stuff with app

var files = fs.readdirSync("models");
files.forEach(function(file) {
  require("models/" + file);
});

var routes = fs.readdirSync("routes");
routes.forEach(function(route) {
  require("routes/" + route)(app);
});

app.listen(80);

Note that normally readdirSync is evil but it's ok to execute blocking calls at startup time (like require) before your listen to your server

Upvotes: 5

Related Questions