Persisting Data with MongoDB

With almost any application written for the web nowadays, a highly interactive application is of limited value if the interaction between its users isn't permanently saved. You have to integrate your application with a proper database to solve this issue. Imagine a case where all of the data for your application (registered users, order transactions, and social interactions) was stored within the temporary memory of the server the application is running on. The moment that server was turned off or rebooted, all of your application data would be lost. Relying on a database to store this data permanently is crucial to any dynamic application.

In this chapter, the following topics will be covered:

  • Connecting to MongoDB
  • An introduction to Mongoose
  • Schemas and models
  • Adding CRUD to our controllers

In the previous chapter, we wrote and accounted for the actual logic of our application. The next step in building our application is to connect it to a database so that our users' interactions and data can be permanently saved and retrieved. Technically, we can get around this by storing data in the memory, but the moment our web server restarts or crashes, all of that data will be lost. Without connecting our application to a database server to persist data, every input interacted by a visitor will be obsolete. Without some kind of database server to store our data, most of the websites we interact with on a daily basis wouldn't even exist.

Here is a general breakdown of how our data is going to be persisted for every visitor interaction in our app:

Consider the preceding diagram, which reflects the typical life cycle of a web application request:

  1. A visitor submits a request to view a page on our application via their web browser.
  2. The Node.js server receives this request and queries a MongoDB server for any data.
  3. The MongoDB server returns the queried data back to our Node.js server.
  4. The Node.js server takes that data, builds it into the view model, and then sends the rendered HTML page back to the browser.
  5. The web browser receives the response from our Node.js server and renders the HTML.
  6. This cycle typically repeats for every interaction by every visitor.

For the purposes of this book, we are using MongoDB as our primary data store, but the reality is that we can use any of the following to store data: MySQL, PostgreSQL, MS SQL, the filesystem, and so on.

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

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