Last time, we looked at using LoopBack with relational databases, allowing you to consume existing data. This time around, we are looking at your options when the data does not have a schema.

I have JSON documents from REST services and NoSQL databases. Can LoopBack get my models from them?

Yes, certainly! Here is an example:

 var ds = require('../data-sources/db.js')('memory');

// Instance JSON document
var user = {
name: 'Joe',
age: 30,
birthday: new Date(),
vip: true,
address: {
street: '1 Main St',
city: 'San Jose',
state: 'CA',
zipcode: '95131',
country: 'US'
},
friends: ['John', 'Mary'],
emails: [
{label: 'work', id: 'x@sample.com'},
{label: 'home', id: 'x@home.com'}
],
tags: []
};

// Create a model from the user instance
var User = ds.buildModelFromInstance('User', user, {idInjection: true});

// Use the model for CRUD
var obj = new User(user);

console.log(obj.toObject());

User.create(user, function (err, u1) {
 console.log('Created: ', u1.toObject());
 User.findById(u1.id, function (err, u2) {
  console.log('Found: ', u2.toObject());
 });
});

Now we understand that we can define the models from scratch, or discover them from relational databases or JSON documents. How can we make sure that the database models are in sync with LoopBack if some of the database models don’t exist or are different? LoopBack has APIs to facilitate the synchronization. We will demonstrate how next time, in the final part 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.