Loopback: Models and Relations
Getting started with loopback without the struggle
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!
Install loopback globally
npm i -g loopback-cli
- Create and navigate to a fresh directory
- Run lb entering your project name, desired version, and application type
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.
By default Loopback holds all data created from the api in memory. We will be using a database instead.
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.
npm i -S loopback-connector-mysql
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.
Some things to note
- Use db as your datasource name. Many config files reference it, so using db prevents your from having to reconfigure all of them.
- Use localhost or 127.0.0.1 for a local database
- Use 3306 for Mysql. That is the default port.
- 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.
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.
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.
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
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
For creating models you can go through and learn the syntax on your own, or you can once again use the cli.
- The Model base class option will be PersistedModel if you are using a database.
- 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.
- The first property that you don’t fill in will cause you to exit cli
- An Id field is auto generated
- 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.
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.
This is the final stretch. We just need a way to get our models into the database. This is where migrations come in.
For migrating our tables I created this file
And ran it with this command
- To migrate a different set of tables I would just change the models array.
- 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
For the auto generated loopback tables, migration is a little different. This file is straight from the docs.
Running with this command
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/
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.