Search code examples
node.jsormmodels

How to exports models with node-orm?


I'm testing node-orm and I can't find the correct way to export models. Here is the model definition (./models/user.js):

var orm = require('orm');

var db = orm.connect('pg://user@localhost/accounts', function(success, db) {
  if (!success) {
    console.log('Could not connect to database.');
    return;
  }

  var User = db.define('user', {
    ... // Model schema
  });

  module.exports = User;
});

And when I try to use it elsewhere (e.g. ./app.js):

var User = require('./models/user');
...

app.get('/test', function(req, res) {
  var user = new User({
    ...
  });
  user.save(function(err, user) {
    ...
  });

  ...
});

Turns out that User is an empty object so node can't call the model constructor. What is the proper way to export a model with node-orm ? That's probably simple but I find anything in the docs…


Solution

  • Your problem is that you're setting your module.exports in a callback function. Node's module loading system specifically states that you cannot do that.

    The orm-node module stores your models in its module exports with the name that you specify for your model. Your example should work if you change your app.js to read:

    require('./models/user');
    var orm = require('orm');
    ...
    
    app.get('/test', function(req, res) {
      var user = new orm.user({
        ...
      });
      user.save(function(err, user) {
        ...
      });
    
      ...
    });
    

    Also note that because your model is initialized in a callback it is not immediately available after you require() your model module. Presumably you'll have completed your database connection and model initialization before you need to process a get of /user.

    Probably the safest way to handle all this would be to make sure your application initialization and listen() are done as a part of that orm.connect() callback.