Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 213
Warren Avatar asked Oct 20 '14 01:10

Warren


People also ask

What is StrongLoop LoopBack?

LoopBack, an open-source Node application framework based on Express. StrongLoop Process Manager and related devops tools for Node applications.

What is model in LoopBack?

A LoopBack model is a JavaScript object with both Node and REST APIs that represents data in backend systems such as databases. Models are connected to backend systems via data sources. You use the model APIs to interact with the data source to which it is attached.

What is repository in LoopBack?

A Repository represents a specialized Service interface that provides strong-typed data access (for example, CRUD) operations of a domain model against the underlying database or service. Note: Repositories are adding behavior to Models.


1 Answers

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
  }
}
like image 110
Miroslav Bajtoš Avatar answered Sep 23 '22 17:09

Miroslav Bajtoš