How to Integrate React Redux + Nodejs/Express RestAPIs + Mongoose ODM – MongoDB CRUD example
In this tutorial, we will build React Redux Http Client & Nodejs/Express RestAPIs Server example that uses Mongoose ODM to interact with MongoDB database and React as a front-end technology to make request and receive response.
Here is an example of a CRUD (Create, Read, Update, Delete) application built with React, Node.js, and MongoDB:
1. Setting up the backend
First, you will need to set up the backend of your application using Node.js and MongoDB. Here’s how you can do this:
Install Node.js and MongoDB on your system.
Create a new Node.js project and install the required dependencies: express, mongodb, and body-parser.
Connect to the MongoDB database using the MongoClient from the mongodb library.
Create a simple Express server that listens for HTTP requests and handles them using appropriate routing and middleware functions.
Create the CRUD routes for your API. For example, you might have routes like /api/items for creating, reading, updating, and deleting items in the database.
Here’s an example of how the server code might look:
const express = require('express'); const mongodb = require('mongodb'); const bodyParser = require('body-parser'); const app = express(); const port = 3000; // Parse incoming request bodies in a middleware before your handlers app.use(bodyParser.json()); // Connect to the MongoDB database mongodb.MongoClient.connect('mongodb://localhost:27017', (err, client) => { if (err) { console.log(err); process.exit(1); } // Save the client reference to reuse the connection const db = client.db('mydatabase'); // Create the CRUD routes for the /items resource app.get('/api/items', (req, res) => { // Read all items from the database db.collection('items').find().toArray((err, items) => { if (err) { console.log(err); res.sendStatus(500); } else { res.send(items); } }); }); app.post('/api/items', (req, res) => { // Create a new item in the database db.collection('items').insertOne(req.body, (err, result) => { if (err) { console.log(err); res.sendStatus(500); } else { res.send(result.ops[0]); } }); }); app.put('/api/items/:id', (req, res) => { // Update an existing item in the database db.collection('items').updateOne({ _id: mongodb.ObjectId(req.params.id) }, { $set: req.body }, (err, result) => { if (err) { console.log(err); res.sendStatus(500); } else { res.sendStatus(204); } }); }); app.delete('/api/items/:id', (req, res) => { // Delete an item from the database db.collection('items').deleteOne({ _id: mongodb.ObjectId(req.params.id) }, (err, result) => {
Related posts:
– Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose
– How to connect React with Redux – react-redux example