LoopBack 4 TodoList Application Tutorial - Add TodoList Model
Page Contents

Building a checklist for your Todo models

A todo item is often grouped into a checklist along with other todo items so that it can be used to measure the progress of a bigger picture that the item is a part of.

A set of data can often be related to another; an entity may be able to provide access to another based on its relationship with the other entity. To take TodoListApplication one step further and establish relations with the existing Todo model as real-world applications often tend to do, we’ll introduce the model TodoList.

We’ll create TodoList model to represent a checklist that contains multiple Todo items. Let’s define TodoList model with the following properties:

  • a unique id
  • a title
  • a color to represent the TodoList with

We can use the lb4 model command and answer the prompts to generate the model for us as follows:

$ lb4 model
? Model class name: TodoList

Let's add a property to TodoList
Enter an empty property name when done

? Enter the property name: id
? Property type: number
? Is ID field? Yes
? Required?: No
? Default value [leave blank for none]:

Let's add another property to TodoList
Enter an empty property name when done

? Enter the property name: title
? Property type: string
? Required?: Yes
? Default value [leave blank for none]:

Let's add another property to TodoList
Enter an empty property name when done

? Enter the property name: color
? Property type: string
? Required?: No
? Default value [leave blank for none]:

Let's add another property to TodoList
Enter an empty property name when done

? Enter the property name:
   create src/models/todo-list.model.ts
   update src/models/index.ts

Model TodoList was created in src/models/

Now that we have our new model, it’s time to define its relation with the Todo model. To TodoList model, add in the following property:

src/models/todo-list.model.ts

@model()
export class TodoList extends Entity {
  // ...properties defined by the CLI...

  @hasMany(Todo)
  todos?: Todo[];

  // ...constructor def...
}

Notice that @hasMany() decorator is used to define this property. As the decorator’s name suggests, this will let LoopBack 4 know that a todo list can have many todo items.

To complement TodoList’s relationship to Todo, we’ll add in todoListId property on Todo model to complete defining the relation on both ends:

src/models/todo.model.ts

@model()
export class Todo extends Entity {
  // ...properties defined by the CLI...

  @property()
  todoListId: number;

  // ...constructor def...
}

Once the models have been completely configured, it’s time to move on to adding a repository for TodoList.

Introduction: TodoList Tutorial

Next step: Add TodoList repository