---
description: Learn how to create models to store data relevant to your application.
---

# Create Persisted Models

## &#x20;**Persisted Models**

Lets create a persisted model calle&#x64;**`Favorite`**.

The difference between us creating an AppUser model earlier and us creating a model called  Favorite in this gitbook notebook is that earlier when we created an AppUser model, it was created using a base model, specifically the User model. Using the User model as a base class provides us additional authentication functionality for the users using our application and the ability for the users to sign up and login to use our website. Using the User base class will encrypt the users password, and will allow us to restrict certain users from hitting certain back-end api routes, ultimately restricting their access to our database.&#x20;

This gitbook notebook assumes that no authentication functionality is needed for these types of  models being created, it's like creating a stock model rather than creating a model using a base class which would've added additional functionality and attributes.

#### **Note:**

{% hint style="warning" %}
The **AppUser** and **Favorite** models are technically both persistent models because the data will continue to exist in the database even if someone turns their computer off.&#x20;
{% endhint %}

### &#x20;**What is a Data Model or Schema?**

A data model schema is nothing more than defining the shape of our data or in other words the properties that the objects or entries to the database will have.  Models in loopback are nothing more than us declaring the property name and its data type.\
\
This is the current example of our **appUser** Models Schema that we created

| <p><strong><code>AppUser Model  {</code></strong><br>   <strong><code>firstName: string,</code></strong><br>   <strong><code>lastName: string,</code></strong><br>   <strong><code>email: string,</code></strong><br>   <strong><code>password: string,</code></strong><br> <strong><code>}</code></strong></p> |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

\
Think of a loopback model as creating a class in **typescript** or **prototype** in javascript. We are defining what properties we need and what type of data each property will be.\
\
Above is an example for a model called **AppUser**. We defined that a **AppUser** model has a property called **`firstName`**, that is expecting the datatype of string, along with other properties and their desired types.&#x20;

{% hint style="danger" %}
In our HTTP post request to our back-end to create an **AppUser** this is the object structure our back-end is expecting; when sending data to the loopback server the properties must be exact in spelling and casing and the data type must match or it will return an error as well.
{% endhint %}



### **Creating A Persisted Model**

**Loopback Documentation:** [**Creating a model**](http://loopback.io/getting-started/)

For our persisted model we want to create a model called **Favorite**. This model called **Favorite** will allow the user to save for example a favorite stock or a favorite movie depending on which third party api you are using for the final project.\
\
In this example a model for saving a **favorite** on your backend is being created. This is a generic example and is equivalent to a movie or a stock you want to save on your backend. It is your choice what properties this model has but at minimum you should have a movie title or stock ticker and any data you want to attach from the third party database as properties so that when you display your favorites on your website the data is ready for displaying rather than having to make an addition http request to the third-party database to get data required to display that favorite.

**Note:**&#x20;

{% hint style="warning" %}
If you chose to use the movie database api for your final project then you should add the movie's id property as well. We do this is so that we can later make another http request to get more data from the third party database regarding a particular **Favorite** model entry.
{% endhint %}

\
**Make sure you are in the backend project folder inside of a terminal**

**Create a model by typing: `$ lb model`**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwLsso0Cd2uIMeBi0mk%2Fimage.png?alt=media\&token=b515e60f-5d5c-4592-af48-6a647a35f36b)

**Now we can enter the name of the model, in our case `favorite`**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwLxppSgC8D1dwYL0VM%2Fimage.png?alt=media\&token=ef75b6c0-18da-4083-9dc5-3c2a2da45678)

**Next up we need to select the datasource our model will be attached to, in our case the mongodb we created earlier.**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwLu_JusJBslz_vbTq3%2Fimage.png?alt=media\&token=acf65435-8ad1-443c-af78-f4bf54e0e3c8)

**The next selection is to use a default base model for our book model. Any selection we make here, our model would inherit its base functionality. In our case we just want a Persisted Model, a stock model that will be stored in the database without inheriting any functionality and nothing more.**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwLvWpKfTLV3iJLJrqs%2Fimage.png?alt=media\&token=f9107598-f6a0-4781-abd7-8ff4e1ecc1b6)

**The next prompt we will select if the model is exposed on our backend. If we select Yes then this model can be accessed from external sources, like an http request, if we were to select no the model is only available within our loopback application. In our case we want to select Yes because we want our angular application to be able to interact with this model on our server.**\
**Hit `Enter` For Yes**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwLwKT9hxwWR4jqi2ZR%2Fimage.png?alt=media\&token=779d577f-be67-42bd-beff-b3a4110330be)

**After exposing our model on our API, we now can pick a custom plural method, for example loopback automatically adds an '**_**s**_**&#x20;' to the model name for the endpoint, so a custom endpoint will be /citys by default verus cities being the proper plural. In this case `favorites` is fine.**\
**Hit `Enter`**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwLyEzuf8o_hmJL0V3N%2Fimage.png?alt=media\&token=f5712e73-a94a-4dfe-a322-d31257b68b74)

**Select common on the next option**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwLzkGSWDElwDGcy0Po%2Fimage.png?alt=media\&token=486ddb02-f26d-4a83-bbeb-7e58fbab4022)

**Now all the basic model setup is done.**\
\
**You should have the image below where we can start adding properties to our model.**\
**\*Note pay careful attention to casing this will matter.**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwM-Em-82PtY15LX9oH%2Fimage.png?alt=media\&token=9cad7545-6a48-4eab-8109-cc50d0c3b488)

**Our first property to add will be a title for this model**

{% hint style="warning" %}
Naming Suggestions:

If you are using 3rd party`movie`api: **`movieTitle`**

If you are using 3rd party`stock`api: **`ticker`**
{% endhint %}

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwMU4Ws-8kaQSWeOhYc%2Fimage.png?alt=media\&token=2c60a75b-fa01-489d-8fb6-188e0318315a)

**Now we select the data type that the property will be, in our case string, because names are strings. It is important when creating a model to understand what you need to store and the proper data type that best fits your model. Select string.**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwMVYrLDku9dNrcffdO%2F-LwMoroe7mp-NzOhFWOn%2Fimage.png?alt=media\&token=54f4d797-522d-45c0-9aa9-bab64cca9f6c)

**Now we have the choice of making a property required or not. If we select no and the property is not present when trying to store data it will still store it in our database. If we select Yes, then our `favorite` must always have a title property in order to be saved to the database.**\
**Enter Yes,  this will make the name property required to save.**

{% hint style="info" %}
**Note:** The capital letter in the parentheses, in our case (N), will automatically be chosen if you clic&#x6B;**`Enter`**
{% endhint %}

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwMUoqJSpDfM8R0ekJH%2Fimage.png?alt=media\&token=8170e5cf-6499-4342-b8f9-a02b3ef7d4d9)

**Our next option is asking us if the `movieTitle` property is empty should loopback enter a default value?**\
**Hit `Enter` for none. We do not want a default value if the name property is blank.**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwL5SKGjNpDMW9ZiX4Q%2F-LwMJPTmlSo-9w1DiqLr%2Fimage.png?alt=media\&token=76862705-7d9b-44c4-b0c3-914a3dcd67a3)

**Repeat the above steps to add other properties relevant to this model:**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwMVYrLDku9dNrcffdO%2F-LwMqlziZ9-Z4DWvl0Jh%2Fimage.png?alt=media\&token=6f7afaf2-ebff-4854-8474-060d3e8bfda4)

{% hint style="warning" %}
When thinking of properties we want to add to this model, we would want to think of linking relevant data we receive from the third party api to the new database you just setup. We would want to store all the relevant third party data that will be displayed on your website as properties on this model. This is because when we make a http call to access all of a user's favorites from our database, the response object will have all the data needed in order for it to be displayed on the website. We wouldn't want to have to make another http request to the third party api again to collect data needed in order for you to present that data on your website.
{% endhint %}

**For example add the following property:**

{% hint style="info" %}
If you are using 3rd party`movie`api: **`thirdPartyMovieId`**

If you are using 3rd party`stock`api: **`ticker`**
{% endhint %}

1. **Type: String**
2. **Required: Yes**
3. **Default Value: None**

**Repeat the steps above to add other properties relevant to this model, look at your response object from the third party api to understand what properties you would like to add for your website!**

**Once done hit `enter` to stop the model setup.**

{% hint style="warning" %}
You can alter the properties of a model at anytime by going to the **`final-project/Final-Project-Bk/common/models`**&#x64;irectory and editing the desired model's _**.json**_ file. It is important to note that if you alter the model you need to make sure you either delete or update the older records in your database so that when you query through your database all the model entries have the same properties on them. If we don't handle this we might not get the results we want.
{% endhint %}

**Restart your backend for the changes to take effect by pressing `ctrl + c` in your terminal on windows and `cmd + c` for mac. After you killed your server start your server up again by typing `node .` .**

**Then go to your loopback explorer, typically its at `http://localhost:3000/explorer`**\


![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwMVYrLDku9dNrcffdO%2F-LwMzR5wesCc4SMTBShB%2Fimage.png?alt=media\&token=8e75bc0a-58e0-45db-89ae-a143d3691fc4)

**Success you have a new route on your backend for the newly created “favorite” model.**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQWPRFQNnwuBibkMRI%2F-LwQXG6sj7L2-AqHLPJb%2Fimage.png?alt=media\&token=b1a2aced-30e2-4b4a-b165-389d95b82866)

### &#x20;**Creating a New Favorite In Loopback Explorer**

**Under the Favorites route click the `post /favorites` option**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQWPRFQNnwuBibkMRI%2F-LwQXWgbBlepA0W-efxq%2Fimage.png?alt=media\&token=937b4d4b-6535-4e53-b25c-b5315799b04b)

\
**The white box is where are have the properties and values for our book. Once you create the object select Try it out**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQWPRFQNnwuBibkMRI%2F-LwQ_Lq1xhedfTsYNq99%2Fimage.png?alt=media\&token=dcc9305b-cd30-47b5-b21c-ba76156b1219)

**Response code 200 means everything went great**

**An http post request to the below URL will create a new book instance.**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQ_scVyUaAxedstUHI%2F-LwQaHf9mTW2dBoV84eD%2Fimage.png?alt=media\&token=bb4e2351-ed25-4f6f-a2fb-9990e6d4c3dd)

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQ_scVyUaAxedstUHI%2F-LwQc_d3xXy-lWUzc-tt%2Floopback-favorite%20model.gif?alt=media\&token=f47a0929-c7ec-46f5-b162-fa66e5398d90)

### &#x20;**Using the endpoint**

Now back in your angular application create a service called movie or stock service in your angular project. This service will deal with our movie/stocks endpoint for your backend.&#x20;

{% hint style="info" %}
This would be a different service than the service that deals with related third party api behaviors such as making http requests to the third party api and potentially storing those states for the entire angular application to use.
{% endhint %}

You will need the above url from the post request from your model.\
You will need to repeat the pattern of your login/register post requests where we were creating a post request to send data. Your goal is to pass data when a user clicks on a movie or stock and they want to save it in the backend.

**Register Example:**

{% content-ref url="register" %}
[register](register)
{% endcontent-ref %}
