Chapter 5. Building a data model with MongoDB and Mongoose

 

This chapter covers

  • Connecting Express/Node applications to MongoDB using Mongoose
  • Defining schemas for a data model using Mongoose
  • Connecting an application to a database
  • Managing databases using the MongoDB shell
  • Pushing a database into a live environment

In chapter 4, you moved your data out of the views and back the MVC path into the controllers. Ultimately, the controllers will pass data to the views, but they shouldn’t store it. Figure 5.1 recaps the data flow in an MVC pattern.

Figure 5.1. In an MVC pattern, data is held in the model, processed by a controller, and then rendered by a view.

For storing the data, you’ll need a database—specifically, MongoDB. This step is the next one in the process: creating a database and a data model.

Note

If you haven’t yet built the application from chapter 4, you can get the code on the chapter-04 branch at https://github.com/cliveharber/gettingMean-2. In a fresh folder in terminal, enter the following command to clone it:

$ git clone -b chapter-04 https://github.com/cliveharber/gettingMean-2.git

You’ll start by connecting your application to a database before using Mongoose to define schemas and models. When you’re happy with the structure, you can add some test data directly to the MongoDB database. The final step is making sure that access to the data store also works when pushed up to Heroku. Figure 5.2 shows the flow of these four steps.

5.1. Connecting the Express application to MongoDB by using Mongoose

5.2. Why model the data?

5.3. Defining simple Mongoose schemas

5.4. Using the MongoDB shell to create a MongoDB database and add data

5.5. Getting your database live

Summary

sitemap