Lesson 15. Connecting Controllers and Models

 

So far, you’ve set up your Node.js application to handle data and store that data in a MongoDB database. With the help of Mongoose, you’ve structured your data with a model and schema. In this lesson, you connect your routes to your controllers and to these models so that you can start to save meaningful data based on your user’s URL requests. First, you build a new controller for subscriber routes. Then you will convert those routes to use JavaScript ES6-enabled promises. Adding promises gives more flexibility to your database calls now and as your application grows. Finally, you wrap up this lesson with new views and a form where subscribers can post their information.

This lesson covers

  • Connecting controllers to models
  • Saving data through a controller action
  • Implementing database queries with promises
  • Handling posted form data
Consider this

Your recipe application is taking shape with Mongoose models to represent data in your database. JavaScript, however, is asynchronous in your application, so database calls require callbacks to run upon completion. Callbacks can be messy, though, especially with complicated queries.

Luckily, you can use multiple other types of syntax to wrap your callbacks and handle returned data or errors in a more elegant way. Promises are a way to do that, and Mongoose offers support for using the promise syntax within your application.

15.1. Creating a controller for subscribers

15.2. Saving posted data to a model

15.3. Using promises with Mongoose

Summary