Using StrongLoop to create a Node.js MySQL application

Share this post:

StrongLoop, an IBM companyThe StrongLoop API Platform is built on top of the open source, a highly-extensible, Node.js API framework. With LoopBack, you can quickly create scalable APIs and database mappings. StrongLoop also has built-in Mobile Backend as a Service (MBaaS) features like push and offline sync, and it has graphical tools for clustering, profiling and monitoring Node apps. StrongLoop runs on top of the Express Node.js web application framework and conforms to the Swagger 2.0 specification.

The recently published tutorial Getting Started with Bluemix and StrongLoop presents videos summarizing the strengths of each product and demonstrating a sample application; the tutorial Getting Started with Node.js LoopBack Framework and IBM Cloudant examines how to leverage IBM Cloudant as a backend data store with the LoopBack framework and StrongLoop Arc tools.

Continuing with same theme as the previous tutorials, this brief tutorial shows the steps of integrating data from a MySQL database with Node.js using the StrongLoop API. We make no assumptions about tooling other than the command line! Once complete, you will be able to browse the generated APIs:

From there you will be able to POST data with the StrongLoop API Explorer and review the results in your database browser of choice.

Before you begin

Beyond the command line, below are the prerequisite tools:

Of course you’ll need a Bluemix account. If you don’t already have one, click the button below:

Before you can use StrongLoop in your app, you must install the StrongLoop command line tools. These include slc, the command shell for the StrongLoop Process Manager, strong-pm, and the LoopBack API Framework, with both a CLI and a GUI. To install the StrongLoop tools, execute the following npm command:

<code>npm install -g strongloop</code>

To verify whether LoopBack is installed successfully, type

<code>slc –v</code>

It should display the version of your StrongLoop installation.

Create a skeletal LoopBack application

Change to your development directory.

<code>cd &lt;development_directory&gt;</code>

Create a new application entitled ‘<alias>-loopback-example’ (e.g. amyla-loopback-example) by using the following command.

<code>slc loopback &lt;alias&gt;-loopback-example</code>

Enter the application name and the installation directory to complete the initialization of your new StrongLoop project. You now have a complete Node.js StrongLoop application. Try to run your application and open the explorer page.

<code>cd &lt;alias&gt;-loopback-example
node server/server.js

If an error similar to “Cannot find module ‘loopback'” occurs, run npm install to install the prerequisite modules in the node_modules directory. Click the show/hide link to show the StrongLoop APIs that come available with your new application:

Install the StrongLoop MySQL connector

Next, we will add MySQL support for the MySQL database to the project, by installing the LoopBack MySQL connector. Run the following command to install the StrongLoop MySQL connector:

<code>cd &lt;alias&gt;-loopback-example
npm install --save loopback-connector-mysql

Configuring the Datasource

Now the appropriate database support is added, you must configure the datasource with your database connection. Create and configure a new datasource named ‘AccountDb’.

<code>slc loopback:datasource AccountDb</code>

Enter to accept the default datasource name. For the database type, select MySQL.

Create a Node.js Application and MySQL Service

Now we have a working StrongLoop application running on our localhost, and we are about to add a MySQL connection to the application, we must first create the MySQL instance that we want to connect to.

If you have already an existing MySQL database instance that you want to use, you can skip this step and use the MySQL credentials of your existing service instead.

I will create a new MySQL database instance in Bluemix. If you do not have a Bluemix account, sign up for a free Bluemix trial.

  • Login to the Bluemix console at
  • Go to the Dashboard.
  • Under ‘Cloud Foundry Apps’ click ‘CREATE APP’.
  • Select ‘WEB’.
  • Select ‘SDK for Node.js’ and click ‘CONTINUE’.
  • Enter the application name ‘<alias>-loopback-example’ at ‘APP NAME’ and click ‘FINISH’.

Wait until the app is finished staging.

  • Once the message ‘Your app is running’ is displayed, click on the Overview page.
  • Click on ‘ADD A SERVICE OR API’ or if you previously already created the MySQL service, click ‘BIND A SERVICE OR API’.
  • Search for ‘MySQL’ or scroll down to the Data & Analytics services.
  • Find and select the ‘ClearDB MySQL Database’ service.
  • Accept the defaults or rename the service and press ‘USE’ and confirm to ‘restage’ the application.

Once you created the service, in the left menu of the application detail page, go to ‘Environmental Variables’ to see the MySQL service credentials. Or go to the Overview page, and in the service window, click the ‘Show Credentials’ link.

Configure the Datasource

In your application directory, open the server/datasources.json file, and add your datasource configuration. Copy the credentials for the ClearDB MySQL service or use your own MySQL Database credentials.

&quot;cleardb&quot;: [
&quot;name&quot;: &quot;MyClearDBMySQLDatabase-5y&quot;,
&quot;label&quot;: &quot;cleardb&quot;,
&quot;plan&quot;: &quot;spark&quot;,
&quot;credentials&quot;: {
&quot;jdbcUrl&quot;: &quot;jdbc:mysql://&lt;database_subdomain&gt;;database&gt;?user=&lt;username&gt;&password=&lt;password&gt;&quot;,
&quot;uri&quot;: &quot;mysql://&lt;username&gt;:&lt;password&gt;@&lt;database_subdomain&gt;;database&gt;?reconnect=true&quot;,
&quot;name&quot;: &quot;&lt;database&gt;&quot;,
&quot;hostname&quot;: &quot;&lt;database_subdomain&gt;;,
&quot;port&quot;: &quot;3306&quot;,
&quot;username&quot;: &quot;&lt;username&gt;&quot;,
&quot;password&quot;: &quot;&lt;password&gt;&quot;

Add the credentials to the server/datasources.json file.

&quot;db&quot;: {
&quot;name&quot;: &quot;db&quot;,
&quot;connector&quot;: &quot;memory&quot;
&quot;AccountDb&quot;: {
&quot;host&quot;: &quot;&lt;database_subdomain&gt;;,
&quot;port&quot;: 3306,
&quot;database&quot;: &quot;&lt;database&gt;&quot;,
&quot;password&quot;: &quot;&lt;password&gt;&quot;,
&quot;name&quot;: &quot;AccountDb&quot;,
&quot;user&quot;: &quot;&lt;username&gt;&quot;,
&quot;connector&quot;: &quot;mysql&quot;

Create the Data Model

Now the database is successfully added and the datasource configured, you can create the data model. The data model describes the schema or the data objects in your application. Each data object will have its own model in StrongLoop. The complete schema is the collection of models. Here we create a data model for the Account object.

<code>slc loopback:model Account</code>

Follow the prompts to configure the data model. For the model’s ‘base class’ use ‘PersistedModel’ and choose to expose the model via the REST API. Add the model properties as follows:

<code>Name: Account
Datasource: AccountDb
Base class: PersistedModel
Expose via REST: Yes
Custom plural form: Leave blank

For Properties on the data model, create the following three properties.

<code>Property name: email
Property type: string
Required? Not required
<code>Property name: createdAt
Property type: date
Required? Not required
<code>Property name: lastModifiedAt
Property type: date
Required? Not required

We now have the database support, the data source and the data model. With these, we can use Object Relation Mapping (ORM) to generate the database schema in MySQL from the data model, using the auto-migrate tool in StrongLoop.

Add a script to create the schema in the database.

Create a bin directory inside the ./server folder in your project root.

<code>cd server
mkdir bin</code>

In the server/bin directory, create a file called automigrate.js with the following code.

<code>var app = require('../server');

var accounts = [
email: '',
createdAt: new Date(),
lastModifiedAt: new Date()
email: '',
createdAt: new Date(),
lastModifiedAt: new Date()

// this loads the accountDb configuration in ~/server/datasources.json
var dataSource = app.dataSources.AccountDb;

// this automigrates the Account model
dataSource.automigrate('Account', function(err) {
if (err) throw err;

// this loads the Account model from ~/common/models/Account.json
var Account = app.models.Account;
var count = accounts.length;
accounts.forEach(function(account) {
// insert new records into the Account table
Account.create(account, function(err, record) {
if (err) return console.log(err);

console.log('Record created:', record);


if (count === 0) {

Create the MySQL Schema

Run the automigrate.js script with the below command to create the table in MySQL.

<code>node server/bin/automigrate.js</code>

After running the above script, connect to your MySQL database with your favorite MySQL client and you should see the table ‘account’ with the three columns: ’email’, ‘createdAt’ and ‘lastModifiedAt’. StrongLoop also added an ‘id’ column. The table has data for the two entries that we created in the script to insert the data:

Run the application

<code>slc run</code>


<code>node server/server.js</code>

and browse to http://localhost:3000/explorer. StrongLoop added a series of APIs that are Swagger compliant to your application to access the Account resource:

We can also use the explorer page to test each API. Click the ‘POST /Accounts’ link to insert new data. Enter a new JSON record and press ‘Try it out!’.

&quot;email&quot;: &quot;;,
&quot;createdAt&quot;: &quot;2015-09-01&quot;,
&quot;lastModifiedAt&quot;: &quot;2015-09-01&quot;

Your StrongLoop application to manage Accounts is done! We just need to still upload and deploy it to Bluemix.

Deploy the StrongLoop app to Bluemix

  • Go to the Bluemix Dashboard and click on the project(that you created earlier).
  • Click on start coding.
  • Download the code of the starter application in Bluemix to your localhost, or clone the Git repository to your localhost.
  • Copy the manifest.yml file of the Bluemix starter application to the root directory of your local StrongLoop application ‘<alias>-loopback-example’. This file contains information used by Cloud Foundry to deploy the Node.js application to Bluemix.
  • Copy the hidden .cfignore file to the root directory of your local StrongLoop application ‘<alias>-loopback-example’.
  • Modify the local StrongLoop ‘package.json’ file to add the ‘cfenv’ dependency and change the start script parameter (see code snippet below)
  • Modify server/server.js file of your local StrongLoop application to include the ‘host’ and ‘port’ read by cfenv. Bluemix makes these parameters available as environment variables. In the code snippet below I modified the server.js generated by StrongLoop to reflect these changes.
  • Remove the node_modules folder from the root directory of your local StrongLoop application.

Code snippet for package.json:

<code>&quot;scripts&quot;: {
&quot;start&quot;: &quot;node server/server.js&quot;,
&quot;pretest&quot;: &quot;jshint .&quot;
&quot;dependencies&quot;: {
&quot;cfenv&quot;: &quot;1.0.x&quot;

Code snippet for server/server.js:

<code>var loopback = require('loopback');
var boot = require('loopback-boot');
// cfenv provides access to your Cloud Foundry environment
// for more info, see:
var cfenv = require('cfenv');
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

var app = module.exports = loopback();
app.start = function() {
// start the web server
return app.listen(appEnv.port, appEnv.bind, function() {
console.log('Web server listening at: %s', app.get('url'));

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)

Connect to Bluemix and login to Bluemix:

<code>cf api
cf login -u &lt;alias&gt; -o &lt;organization&gt; -s &lt;space&gt;

Push your application to Bluemix using the cf push command:

<code>cf push &lt;alias&gt;-loopback-example</code>

The cf push should kick off a git commit, git push and build and deploy on Bluemix. Check your Bluemix Dashboard or your JazzHub ‘Build & Deploy’ page to confirm your application is now running successfully on Bluemix!

More stories
May 1, 2019

Two Tutorials: Plan, Create, and Update Deployment Environments with Terraform

Multiple environments are pretty common in a project when building a solution. They support the different phases of the development cycle and the slight differences between the environments, like capacity, networking, credentials, and log verbosity. These two tutorials will show you how to manage the environments with Terraform.

Continue reading

April 29, 2019

Transforming Customer Experiences with AI Services (Part 1)

This is an experience from a recent customer engagement on transcribing customer conversations using IBM Watson AI services.

Continue reading

April 26, 2019

Analyze Logs and Monitor the Health of a Kubernetes Application with LogDNA and Sysdig

This post is an excerpt from a tutorial that shows how the IBM Log Analysis with LogDNA service can be used to configure and access logs of a Kubernetes application that is deployed on IBM Cloud.

Continue reading