dresende / node-orm2

Object Relational Mapping
http://github.com/dresende/node-orm2
MIT License
3.07k stars 379 forks source link

How to do ORM2 split file model definition? #693

Closed tratnayake closed 8 years ago

tratnayake commented 8 years ago

Hello all. If I have the following in my app.js of my express app:

app.use(orm.express(opts, {
    define: function (db, models, next) {
            db.load("./models/index", function (err)
              {
                  if (err)   
                      throw err;
                  db.sync();
                  console.log("DB Sync'd!")
                  //console.log(models);
                  console.log(db.models);
              })
    next();        
    }
}))

as suggested in: https://github.com/dresende/node-orm2/issues/458

and demonstrated in: https://github.com/lastMove/MealPlanner/blob/master/MealPlan/app.js

Why is it that I can't access my models when handling a route with (for example) req.db.models.user? The request doesn't even seem to get req.db (it's undefined)

tratnayake commented 8 years ago

Figured it out (if anyone arrives on this same issue sometime later). The code snippet above (app.use with model definitions) needs to be posted BEFORE the router is called in the app.js.

This is also mentioned in the orm2 documentation however I skimmed over that part and missed it.