Chapter 7. Data Storage and Retrieval

In the previous two chapters, we built a small and somewhat useful application for storing notes, and then made it work on mobile devices. While the application works reasonably well, it doesn't store those notes anywhere for long-term storage, which means the notes are lost when you stop the server. Further, if you run multiple instances of Notes, each instance has its own set of notes; this makes it difficult to scale the application to serve lots of users.

The typical next step in such an application is to introduce a database tier. Databases provide long-term reliable storage, while enabling easy sharing of data between multiple application instances.

In this chapter, we will look at database support in Node.js in order to provide these capabilities:

  • The user must see the same set of notes for any Notes instance accessed
  • Reliably store notes for long-term retrieval

We'll start with the Notes application code used in the previous chapter. We started with a simple, in-memory data model using an array to store the notes, and then made it mobile friendly. In this chapter, we'll add additional model implementations using several database engines.

Let's get started!

The first step is to duplicate the code from the previous chapter. For instance, if you were working in chap06/notes, duplicate that to be chap07/notes.

Data storage and asynchronous code

It's worth discussing the concept of asynchronous code again, since external data storage systems, by definition, require asynchronous code. The access time to retrieve data from disk, from another process, or from a database always takes enough time to require deferred execution.

Accessing in-memory data takes a few clock cycles, making it possible to directly operate on in-memory data without delays that would prevent a Node.js server from handling events. Data stored anywhere else, even in the memory space of another process, requires a delay to access that data. This is long enough to prevent the Node.js server from handling events. The rule of thumb is that asynchronous coding is not required for data retrievable within microseconds. But when the time to retrieve the data takes longer, asynchronous coding is required. Since Node.js is a single-thread system, application code cannot block the event loop.

The existing Notes application used an in-memory data store. Going by that rule of thumb, we can write the Notes model with non-asynchronous code, but instead we wrote it to use Promises for asynchronous access. That's because we thought ahead and knew we will extend the Notes application to use a database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset