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
In the server folder create a file .env, entering the URI for your mLab database along with the username and password you created
Next we need to integrate Mongoose and setup a connection to the db.
Once the server restarts you should see in the console window that it has successfully connected.
Next, we’ll create a model for our news. Make a new folder within the server directory called models and create a file called News.js
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
This will export 2 functions, 1 for returning all News, one for returning a single news story.
We’ll now alter our News route to use the controller
We need to now make a few changes to our client components to use _id instead of id
Later on we will change the above to use a slug based on the title but for now we will continue on using the id.
With that done we now have our API returning data from the database back to our client. Currently we have no news however…
Let’s start by add create functionality to our NewsController on the server
In our routes/news.js we’ll add a post route and use this new controller create function.
We next need to integrate some middleware for parsing our incoming request body. For this we will use body-parser
In App.js on our server, we’ll then apply the middleware before our news route.
Switching to the client , lets add an action for making the POST request to our API
Lets now make a simple news form so that anyone with news can submit a story. In the components/containers folder create the following file called NewsSubmit.js
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
You should now be able to create news storys.
Next we are going to add the ability for someone to comment on the news story. Before we can do that we are going to need register and login..