Loopback: Models and Relations

Keeping up with a full stack worth of technologies can be difficult, especially if you strongly favor one side. I love design so naturally I love front end work. Personally, I would like the backend to just work, freeing me to focus on my strengths.

That’s where Loopback comes in. It takes model data and generates a corresponding api. In this article I will go over getting started with loopback through a simple 🏫 school example!

Getting Started

Install loopback globally

npm i -g loopback-cli

Initialize project

  1. Create and navigate to a fresh directory
  2. Run lb entering your project name, desired version, and application type
Project Initialization

Assuming you chose the api-server option like me, you will have 5 preloaded models. These include User, AccessToken, ACL, RoleMapping, Role. User is the only one I have interacted with. Later, it will be used to manipulate users in the database.

Configure Database

Loopback Connectors🛰️

By default Loopback holds all data created from the api in memory. We will be using a database instead.

Connector Types

According to the website. These are the options available. Each of the different data sources has a corresponding connector. Think of them as extensions to Loopback for each of the different data source types. I will be using MySql. But feel free to use whatever you prefer.

Installing Connector

npm i -S loopback-connector-mysql

Loopback Datasources📡

Loopback lets you configure different data sources. Additionally, it lets you configure different models for different data sources. In this article we will only be using a local database, which all of our models will connect to.

Configure a Datasource

Before you begin delete existing datasource in ./server/datasources.json. Then run lb datasource following along with the cli. Note the values you enter should correspond to your database.

Datasource Cli

Some things to note

  1. Use db as your datasource name. Many config files reference it, so using db prevents your from having to reconfigure all of them.
  2. Use localhost or 127.0.0.1 for a local database
  3. Use 3306 for Mysql. That is the default port.
  4. Use a database that corresponds to your model/schema. I chose School-Database because that is the name of my Schema in MySql. *Note* Mysql schemas are lower case, so despite the value I entered a schema called school-database will be created.
Datasource Created

This is the file generated from the jargon above. It can be created manually, and assuming you retain the name db you will not have to change any other files for datasource creation.

Model Design

This is the reason I am making this article. Relationships can get complicated just like in real life, but I have conquered the hairy stuff so you don’t have to. I will go through, One to One, Many to One, and Many to Many relationships.

Our Model

For our model I wanted to keep it simple without leaving any relationship types out. Continuing on the school example, we have the following model

Database Diagram

I will be highlighting

  • The One to One, Student to Locker relationship
  • The One to Many, Class to Teacher relationship
  • The Many to Many, Student to Class relationship via Enrollment

Creating models

For creating models you can go through and learn the syntax on your own, or you can once again use the cli.

lb model

Model Generation cli
Resulting Models Generated
  1. The Model base class option will be PersistedModel if you are using a database.
  2. The Common vs Server model option changes were the models are saved. Common is intended for sharing models between front and back end. It places models in the common directory at the same level as the server and client directories. The server options places them in the server folder.
  3. The first property that you don’t fill in will cause you to exit cli
  4. An Id field is auto generated
  5. If you make a mistake just delete the corresponding files in your models folder, and clear the corresponding object value in model-config.json

One to One

Nothing to say about this. Loopback is super intuitive here.

One to Many

By nature Many to Many relationships are just two One to Many relationships. You can see this on the database diagram above! I think that the through table option seen below can do something similar, but I have not found a use case, and the docs always leave it at No.

Many to Many

In some cases you want to add fields to your join table. In our example, we could add a datetime to the enrollment table referencing what semester the student took a class. For that we would want to create hasMany/belongsTo relationships between student and enrollment, and class and enrollment. This in total this is six entries combined with the has and belongs to many entries seen below.

Customizations

Now that your models have been created you are almost ready to migrate. Any changes that you feel necessary can be made in the Model directory. Personally, I like my relationships columns to be in snake case for Mysql. To do this I go through all the model files overriding the implicitly generated foreign key columns.

Override the implicit creation of the studentId column

Migration 🐦

This is the final stretch. We just need a way to get our models into the database. This is where migrations come in.

Our Tables

For migrating our tables I created this file

Entity Table Migration

And ran it with this command

Note

  1. To migrate a different set of tables I would just change the models array.
  2. If you change the models after you have data in your database don’t run this. In general migrations clear your database. Check out autoupdate in the docs

Credential Tables

For the auto generated loopback tables, migration is a little different. This file is straight from the docs.

Credential Table Migration

Running with this command

💥Boom💥

Assuming you created the Schema before running these commands your MySql database will look something like this. Additionally if you run npm start you should see your api hosted at localhost://3000

Loopback also provides some awesome functionality through something called explorer. It allows you to go through each of your routes and well, explorer them. Check it out at localhost://3000/explorer/

Loopback Explorer

Conclusion

Wow. That was serious journey. I am glad you stuck through it. Loopback has much more to offer, which I will hopefully be explaining in future articles, but hope this got you on your feet.

This is my first article/tutorial anywhere in general, so if you have recommendations or critiques please shoot me a pm! Additionally, if you have a question, ask it in the comments and I will do my best to help.

🤟Josh

Joshuawootonn.com

Github Repo

--

--

--

https://joshuawootonn.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to go about the development of product features using the Agile methodology: Incremental and…

^DOWNLOAD E.B.O.O.K.# Introduction to Materials Science for Engineers (8th Edition) TXT,PDF,EPUB

A PARALLEL MATH PROGRAM USING ANEKATHREADS

Sealed Classes in Kotlin

Securing APIs in a Cloud Native Environment

HTTP Request and Response with Flask

AWS vs Azure — Key Differences in 2021

Ansible Dynamic Inventory for AWS EC2 instances attached to ELB

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Joshua Wootonn

Joshua Wootonn

https://joshuawootonn.com

More from Medium

Intro to GraphQL

Building a Date Pipeline for Instagram Comments — Part 1

Export data from DynamoDB

First Impressions on Clickhouse Json Datatype