Create Persisted Models
Learn how to create models to store data relevant to your application.
Persisted Models
Lets create a persisted model calledFavorite
.
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.
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:
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.
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
AppUser Model {
firstName: string,
lastName: string,
email: string,
password: string,
}
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.
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.
Creating A Persisted Model
Loopback Documentation: Creating a model
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:
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.
Make sure you are in the backend project folder inside of a terminal
Create a model by typing: $ lb model
Now we can enter the name of the model, in our case favorite
Next up we need to select the datasource our model will be attached to, in our case the mongodb we created earlier.
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.
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
After exposing our model on our API, we now can pick a custom plural method, for example loopback automatically adds an 's ' 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
Select common on the next option
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.
Our first property to add will be a title for this model
Naming Suggestions:
If you are using 3rd partymovie
api: movieTitle
If you are using 3rd partystock
api: ticker
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.
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.
Note: The capital letter in the parentheses, in our case (N), will automatically be chosen if you clickEnter
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.
Repeat the above steps to add other properties relevant to this model:
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.
For example add the following property:
If you are using 3rd partymovie
api: thirdPartyMovieId
If you are using 3rd partystock
api: ticker
Type: String
Required: Yes
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.
You can alter the properties of a model at anytime by going to the final-project/Final-Project-Bk/common/models
directory 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.
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
Success you have a new route on your backend for the newly created “favorite” model.
Creating a New Favorite In Loopback Explorer
Under the Favorites route click the post /favorites
option
The white box is where are have the properties and values for our book. Once you create the object select Try it out
Response code 200 means everything went great
An http post request to the below URL will create a new book instance.
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.
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.
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:
Last updated