How do I get a hold of a Strongloop loopback model?

Warren picture Warren · Oct 20, 2014 · Viewed 6.9k times · Source

This is maddening, how do I get a hold of a loopback model so I can programmatically work with it ? I have a Persisted model named "Notification". I can interact with it using the REST explorer. I want to be able to work with it within the server, i.e. Notification.find(...). I execute app.models() and can see it listed. I have done this:

var Notification = app.models.Notification;

and get a big fat "undefined". I have done this:

var Notification = loopback.Notification;
app.model(Notification);
var Notification = app.models.Notification;

and another big fat "undefined".

Please explain all I have to do to get a hold of a model I have defined using:

slc loopback:model

Thanks in advance

Answer

Miroslav Bajtoš picture Miroslav Bajtoš · Oct 24, 2014

You can use ModelCtor.app.models.OtherModelName to access other models from you custom methods.

/** common/models/product.js **/
module.exports = function(Product) {
  Product.createRandomName = function(cb) {
    var Randomizer = Product.app.models.Randomizer;
    Randomizer.createName(cb);
  }

  // this will not work as `Product.app` is not set yet
  var Randomizer = Product.app.models.Randomizer;
}

/** common/models/randomizer.js **/
module.exports = function(Randomizer) {
  Randomizer.createName = function(cb) {
    process.nextTick(function() { 
      cb(null, 'random name');
    });
  };
}

/** server/model-config.js **/
{
  "Product": {
    "dataSource": "db"
  },
  "Randomizer": {
    "dataSource": null
  }
}