Chapter 5. Building a data model with MongoDB and Mongoose

 

This chapter covers

     
     
     

    How Mongoose helps bridge an Express/Node application to a MongoDB database

    • 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
    • Using the correct database depending on the environment, distinguishing between local and live versions of an application

    In chapter 4 we ended up by moving our data out of the views and backward down 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 we’ll need a database, specifically MongoDB. So this is our next step in the process: creating a database and data model.


    If you haven’t yet built the application from chapter 4, you can get the code from GitHub on the chapter-04 branch at github.com/simonholmes/getting-MEAN. In a fresh folder in terminal the following command will clone it:

    $ git clone -b chapter-04 https://github.com/simonholmes/getting-MEAN.git

    5.1. Connecting the Express application to MongoDB using Mongoose

     
     

    5.1.1. Adding Mongoose to our application

     
     
     
     

    5.1.2. Adding a Mongoose connection to our application

     
     
     
     

    5.2. Why model the data?

     
     
     

    5.2.1. What is Mongoose and how does it work?

     

    5.3. Defining simple Mongoose schemas

     

    5.3.1. The basics of setting up a schema

     
     

    5.3.2. Using geographic data in MongoDB and Mongoose

     
     

    5.3.3. Creating more complex schemas with subdocuments

     
     

    5.3.4. Final schema

     
     
     

    5.3.5. Compiling Mongoose schemas into models

     
     
     

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

     
     

    5.4.1. MongoDB shell basics

     
     
     
    sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest