16.13. Creating a CRUD with NodeJS and MongoDB: Application Deployment
Page 97 | Listen in audio
After having covered the basic and intermediate concepts of creating APIs in NodeJS, we reached the crucial point of our e-book course: the creation of a CRUD (Create, Read, Update, Delete) with NodeJS and MongoDB, and the deploy of our application. This chapter 16.13 will guide you step by step to accomplish this very important task.
Preparing the Environment
First, make sure you have NodeJS and MongoDB installed on your system. If not, you can download and install them from their official websites. In addition, we will need Postman to test our APIs, and Heroku CLI to deploy our application.
Creating the NodeJS Project
To create a new NodeJS project, open the terminal and navigate to the directory where you want to create the project. Then run the "npm init" command to initialize a new project. This will create a new "package.json" file in your directory, which contains information about your project and the dependencies it needs.
Installing Dependencies
For our project, we will need some dependencies: express, mongoose, body-parser and nodemon. To install them, run the command "npm install express mongoose body-parser nodemon".
Creating the Express Server
Now, let's create our Express server. Create a new file called "server.js" and add the following code:
```javascript const express = require('express'); const app = express(); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); }); ```This code creates a new Express server that listens on port 3000.
Connecting to MongoDB
To connect to MongoDB, we need to use Mongoose, a library that allows us to interact with MongoDB in an easy and direct way. Add the following code to your "server.js":
```javascript const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('Could not connect to MongoDB', err)); ```This code connects to MongoDB running locally on your machine.
Creating the CRUD
To create the CRUD, we first need to define a model for our data. Create a new file called "user.model.js" and add the following code:
```javascript const mongoose = require('mongoose'); const User = mongoose.model('User', new mongoose.Schema({ name: String, email: String, password: String })); module.exports = User; ```This code defines a user template with three fields: name, email and password.
Now, let's create the routes for our CRUD. Create a new file called "user.routes.js" and add the following code:
```javascript const express = require('express'); const router = express.Router(); const User = require('./user.model'); router.post('/', async (req, res) => { let user = new User({ name: req.body.name, email: req.body.email, password: req.body.password }); user = await user.save(); res.send(user); }); router.get('/', async (req, res) => { const users = await User.find(); res.send(users); }); router.get('/:id', async (req, res) => { const user = await User.findById(req.params.id); if (!user) return res.status(404).send('The user with the given ID was not found.'); res.send(user); }); router.put('/:id', async (req, res) => { const user = await User.findByIdAndUpdate(req.params.id, { name: req.body.name, email: req.body.email, password: req.body.password }, { new: true }); if (!user) return res.status(404).send('The user with the given ID was not found.'); res.send(user); }); router.delete('/:id', async (req, res) => { const user = await User.findByIdAndRemove(req.params.id); if (!user) return res.status(404).send('The user with the given ID was not found.'); res.send(user); }); module.exports = router; ```This code creates the routes to create, read, update and delete users.
Application Deployment
Finally, let's deploy our application. For this, we are going to use Heroku, a cloud application hosting platform. First, we need to create a file called "Procfile" in our project's root directory. This file tells Heroku how to start our application. Add the following code to the "Procfile":
``` web: node server.js ```Next, we need to initialize a new Git repository in our project. Run the commands "git init" and "git add ." to add all files to the repository. Then run "git commit -m 'Initial commit'" to commit the files.
Now, we need to create a new application on Heroku. To do this, run the command "heroku create". This will create a new application and add a new Git remote called "heroku" to your repository.
Finally, we can deploy our application. To do this, run the command "git push heroku master". This will send our application code to Heroku, which will build and launch the application.
Congratulations! You've just created and deployed a CRUD application with NodeJS and MongoDB! You can now access your application at the address Heroku provided.
Now answer the exercise about the content:
What is the process for creating a CRUD (Create, Read, Update, Delete) with NodeJS and MongoDB as described in the e-book course?
You are right! Congratulations, now go to the next page
You missed! Try again.
Next page of the Free Ebook: