NodeJS-React-Redux Tutorial - Part 4: MongoDB and Mongoose

In part 4 of this series we will setup MongoDB for use with our news API

1.7 MongoDB and Mongoose

Next we need a database. The easiest way to do this is to use a cloud hosted database. Head over to mlab.com and signup for an account, and create a new free sandbox database and then create a new database user

With that setup we’ll next install Mongoose, an ORM we will use for MongoDB. We’ll also install dotenv so that we can store our DB URL as an environment variable and have it loaded in.

Run the following in your server directory

npm install mongoose dotenv --save

In the server folder create a file .env, entering the URI for your mLab database along with the username and password you created

We’ll also want a controller for our News. Create another folder in server and call it controllers. Within that folder create a new NewsController.js

constNews=require('../models/News')module.exports={find:function(params,callback){News.find(params,'_id title teaser',function(err,results){if(err){callback(err,null);return;}callback(null,results);})},findById:function(id,callback){News.findById(id,function(err,results){if(err){callback(err,null);return;}callback(null,results);})}}

This will export 2 functions, 1 for returning all News, one for returning a single news story.

This component has a very basic form. Whenever a form element is changed the component will update a state object. When the submit button is hit it will dispatch the action and
then redirect to the homepage (You’ll note the use of withRouter in the export statement in order to make this.props.history available)

The final step to make our create news work is to add the new component into our client router