Using Databases
In this chapter, I will demonstrate how Node.js applications can use a relational database to store and query data. This chapter explains how to work directly with a database by executing SQL queries, and how to take a more hands-off approach with an Object Relational Mapping (ORM) package. Table 12.1 puts this chapter into context.
Table 12.1: Putting databases into context
Question |
Answer |
What are they? |
Databases are the most common means of persistently storing data. |
Why are they useful? |
Databases can store large volumes of data and enforce a data structure that makes it possible to perform efficient queries. |
How are they used? |
Databases are managed by database engines, which can be installed as npm packages, run on dedicated servers, or consumed as cloud services. |
Are there any pitfalls or limitations? |
Databases can be complex and require additional knowledge, such as being able to formulate queries in SQL. |
Are there any alternatives? |
Databases are not the only way to store data, but they are the most common, and, generally, the most effective because they are robust and scale up easily. |
Table 12.2 summarizes what we will do in the chapter.
Table 12.2: Chapter summary
Problem |
Solution |
Listing |
Store data persistently. |
Use a database. |
7, 8, 12, 13 |
Simplify the process of changing how data is stored. |
Use a repository layer. |
9–11 |
Display stored data. |
Include query results when rendering templates. |
14, 15 |
Prevent user-submitted values from being interpreted as SQL. |
Use query parameters. |
16, 17 |
Ensure that data is updated consistently. |
Use a transaction. |
18–21 |
Use a database without needing to write SQL queries. |
Use an ORM package and describe the data used by the application using JavaScript code. |
22–25, 27, 28 |
Perform operations that are too complex to describe using model classes. |
Use the ORM package facility for executing SQL. |
26 |
Query for and update data using an ORM. |
Use the methods defined by the model classes, with constraints specified using JavaScript objects. |
29–32 |