16. Creating a CRUD with NodeJS and MongoDB
Page 84 | Listen in audio
This chapter of our e-book is dedicated to a fundamental aspect of developing APIs with NodeJS: creating a CRUD (Create, Read, Update, Delete) using MongoDB as a database. Let's cover step by step how to create, read, update and delete data in a MongoDB database using NodeJS.
Before we get started, it's important to understand what MongoDB is. MongoDB is a document-oriented database that stores data in BSON documents, a binary representation of JSON. This makes it very flexible and scalable, perfect for working with NodeJS.
Configuring the Environment
First, we need to install NodeJS and MongoDB on our system. Once installed, let's create a new NodeJS project and install some dependencies. We'll use 'Express' to create the server, 'mongoose' to interact with MongoDB, and 'body-parser' to parse the body of HTTP requests.
$ npm init $ npm install express mongoose body-parser
After installing these dependencies, let's set up our Express server and connect to MongoDB using Mongoose.
const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const app = express(); mongoose.connect('mongodb://localhost/crud-nodejs-mongodb', {useNewUrlParser: true, useUnifiedTopology: true}); app.use(bodyParser.json()); app.listen(3000, () => console.log('Server running on port 3000'));
Creating the Data Model
Before we can work with our data, we need to define a data model. Let's create a 'User' template with 'name' and 'email' fields.
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserSchema = new Schema({ name: String, email: String }); module.exports = mongoose.model('User', UserSchema);
Creating the CRUD Routes
Now that we have our data model, we can create our CRUD routes. Let's create a 'routes.js' file and import our 'User' model.
const express = require('express'); const User = require('./models/User'); const router = express.Router();
Let's start with the 'Create' route. This route will receive a POST request with the user's data and create a new user in the database.
router.post('/users', async (req, res) => { const user = new User(req.body); await user.save(); res.json({status: 'User Created'}); });
The 'Read' route will fetch all users from the database and return a JSON response with the user data.
router.get('/users', async (req, res) => { const users = await User.find(); res.json(users); });
The 'Update' route will receive a PUT request with the userid and the new user data. It will find the user in the database and update its data.
router.put('/users/:id', async (req, res) => { await User.findByIdAndUpdate(req.params.id, req.body); res.json({status: 'User Updated'}); });
Finally, the 'Delete' route will receive a DELETE request with the userid. It will find the user in the database and remove it.
router.delete('/users/:id', async (req, res) => { await User.findByIdAndRemove(req.params.id); res.json({status: 'User Deleted'}); });
With that, we have a complete CRUD with NodeJS and MongoDB. This is a basic example, but you can expand on this to suit your needs. We hope this chapter was helpful for you to learn how to create a CRUD with NodeJS and MongoDB.
Now answer the exercise about the content:
What is the purpose of CRUD in API development with NodeJS and MongoDB?
You are right! Congratulations, now go to the next page
You missed! Try again.
Next page of the Free Ebook: