Model design
- Node.js course
- Intermediate
- Lesson 65/116
- 6 min
Design the skeleton of Book and Member models.
Project: Library API
In this 5-lesson project you will build a library API. Each lesson adds one piece, and by the final lesson you will have a working API. You will add the data model, then the Express app, CRUD routes, middleware and error handling.
The first lesson is model design: setting up a data structure for books. For a simple API in Node.js, keeping data in an in-memory array is enough. Each book is an object: { id: 1, title: "Node.js" }. You define an empty array called books and add books with books.push(). This way the routes in later lessons can read and write this array.
Adding elements to an array
The simplest way to add an element to an array in JavaScript is the push method. Writing books.push({ id: 1, title: "Node.js" }) appends the object to the end of the array.
After adding, you can access the first element with books[0]. books[0].title gives the title of the first book. These are the basic data operations of the API: add (push), read (index). In later lessons we will connect this array to Express routes; but first we verify the data model works with console.log. Each lesson's starting code will contain the previous lesson's solution, so the API grows step by step.
Practice Set up the data model
Define an empty array named books. Add the object { id: 1, title: "Node.js" } with books.push(). Print books[0].title with console.log.
Starter code
// Define the books array (empty)
// write here
// Add a book object (id: 1, title: "Node.js")
// write here
// Print the first book's title
// write hereSample solution
const books = [];
books.push({ id: 1, title: "Node.js" });
console.log(books[0].title);Expected output
Node.js
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does books.push() do?
books.push(item)- Adds an element to the array Correct answer
- Returns the array length
- Deletes the array
- Sorts the array
Explanation: push adds a new element to the end of the array.
2 Add a book to books
books.____({ id: 1, title: "Node.js" });
books.push({ id: 1, title: "Node.js" });
Explanation: push adds the book object to the array.
3 Match each piece to its role
| Term | Meaning |
|---|---|
books |
Book array |
push |
Adds an element |
id |
Book number |
title |
Book title |