In the prior part of this 5-part series, we looked at schema definitions and defined a model using an in-memory source to mock up the data access. This time around, we are looking at model discovery with existing  relational databases or JSON documents.

I have data in an Oracle database. Can LoopBack figure out the models and expose them as APIs to my mobile applications?

LoopBack makes it surprisingly simple to create models from existing data, as illustrated below for an Oracle database. First, the code sets up the Oracle data source. Then the call to discoverAndBuildModels() creates models from the database tables. Calling it with associations: true makes the discovery follow primary/foreign key relations.

var loopback = require('loopback');
var ds = loopback.createDataSource('oracle', {
  "host": "demo.strongloop.com",
  "port": 1521,
  "database": "XE",
  "username": "demo",
  "password": "L00pBack"
});

// Discover and build models from INVENTORY table
ds.discoverAndBuildModels('INVENTORY', {visited: {}, associations: true},
function (err, models) {
  // Now we have a list of models keyed by the model name
  // Find the first record from the inventory
  models.Inventory.findOne({}, function (err, inv) {
    if(err) {
      console.error(err);
      return;
    }
    console.log("\nInventory: ", inv);
    // Navigate to the product model
    inv.product(function (err, prod) {
      console.log("\nProduct: ", prod);
      console.log("\n ------------- ");
    });
  });
});

For more information, please check out:

http://wiki.strongloop.com/display/DOC/LoopBack+data+sources+and+connectors#LoopBackdatasourcesandconnectors-Discoveringmodeldefinitionsfromadatasource

Discovery from relational databases is a quick way to consume existing data with well-defined schemas. However, some data stores don’t have schemas; for example, MongoDB or REST services. LoopBack has another option here. Find out more next time, when we will take a look at models by instance introspection in part 4 of this series.

What’s next?

  • What’s in the upcoming Node v0.12 release? Six new features, plus new and breaking APIs.
  • Ready to develop APIs in Node.js and get them connected to your data? Check out the Node.js LoopBack framework. We’ve made it easy to get started either locally or on your favorite cloud, with a simple npm install.
  • Need training and certification for Node? Learn more about both the private and open options StrongLoop offers.