16.4. Creating a CRUD with NodeJS and MongoDB: Creating the NodeJS Project
Page 88 | Listen in audio
One of the key features that makes NodeJS an excellent choice for API development is its ability to handle I/O operations efficiently. In this chapter, we are going to discuss how to create a CRUD (Create, Read, Update, Delete) with NodeJS and MongoDB. Let's start with creating the NodeJS project.
Creating the NodeJS Project
To get started, you need to have NodeJS and NPM (Node Package Manager) installed on your system. You can download and install them from the official NodeJS website. Once installed, you can verify the installation by running the following commands in your terminal:
node -v npm -v
If both commands return a version, the installation was successful. Now let's create a new NodeJS project. To do this, create a new directory for your project and navigate to it using the terminal. Then initialize a new NodeJS project with the following command:
npm init -y
This will create a new 'package.json' file in your project directory. This file is used to manage your project's dependencies.
Installing Dependencies
For this project, we will need some dependencies. The first is Express, a NodeJS framework that facilitates the creation of APIs. To install it, execute the following command:
npm install express
Next, we'll need Mongoose, an ORM (Object-Relational Mapping) that facilitates interaction with MongoDB. To install it, run the following command:
npm install mongoose
Creating the Express Server
After installing the dependencies, let's create our Express server. Create a new file called 'server.js' and add the following code:
const express = require('express'); const app = express(); const port = 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); });
This is a basic Express server that listens on port 3000. You can start the server with the following command:
node server.js
Creating the Mongoose Template
Before we can interact with MongoDB, we need to define a Mongoose model. This model represents the structure of our data. For this example, let's create a model for a 'User'. Create a new file called 'User.js' and add the following code:
const mongoose = require('mongoose'); const UserSchema = new mongoose.Schema({ name: String, email: String, password: String, }); module.exports = mongoose.model('User', UserSchema);
This is a basic template that defines a 'User' with a name, email and password.
Connecting to MongoDB
Before we can use our model, we need to connect to MongoDB. Add the following code to 'server.js':
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true });
This will connect to MongoDB running locally on port 27017. If the connection is successful, you can start using your model to create, read, update, and delete users in MongoDB.
Creating CRUD Routes
The next step is to create the CRUD routes. Each route will be responsible for a specific operation. For example, the 'POST /users' route will be used to create a new user, while the 'GET /users/:id' route will be used to read a specific user. Add the following routes to 'server.js':
const User = require('./User'); app.post('/users', async (req, res) => { const user = new User(req.body); await user.save(); res.send(user); }); app.get('/users', async (req, res) => { const users = await User.find(); res.send(users); }); app.get('/users/:id', async (req, res) => { const user = await User.findById(req.params.id); res.send(user); }); app.put('/users/:id', async (req, res) => { const user = await User.findByIdAndUpdate(req.params.id, req.body); res.send(user); }); app.delete('/users/:id', async (req, res) => { await User.findByIdAndDelete(req.params.id); res.send({ message: 'User deleted' }); });
With these routes, you have a complete CRUD with NodeJS and MongoDB. Now you can create, read, update and delete users using your API.
In summary, creating a CRUD with NodeJS and MongoDB is a simple and straightforward process. With NodeJS, you can create efficient and scalable APIs, while MongoDB allows you to efficiently store and retrieve data. By combining the two, you can create powerful APIs that can handle large volumes of data and traffic.
Now answer the exercise about the content:
What is the process to create a CRUD with NodeJS and MongoDB?
You are right! Congratulations, now go to the next page
You missed! Try again.
Next page of the Free Ebook: