CRUD Operations with Node.js, Express, and MongoDB
Node.js is a popular runtime environment for building server-side applications, and it is often used with Express, a minimalist web framework, and MongoDB, a NoSQL database. In this article, we will explore how to perform CRUD (Create, Read, Update, Delete) operations with Node.js, Express, and MongoDB.
Setting up the Environment
Before we can start working on CRUD operations, we need to set up our environment. First, we need to install Node.js and MongoDB on our system. Once that is done, we can create a new Node.js project and install Express and the MongoDB driver for Node.js using npm.
// Create a new Node.js project
mkdir nodejs-projects
cd nodejs-projects
npm init -y
// Install Express and MongoDB driver
npm install express mongodb
Connecting to MongoDB
After setting up the environment, we need to connect our Node.js application to MongoDB. We can do this by creating a new connection to the MongoDB instance and specifying the database we want to use.
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydb';
// Connect to MongoDB
MongoClient.connect(url, function (err, client) {
if (err) throw err;
const db = client.db(dbName);
// Perform CRUD operations here
});
Performing CRUD Operations
With the connection established, we can now perform CRUD operations on our MongoDB database using Node.js and Express. We can create new documents, read existing documents, update documents, and delete documents using the MongoDB driver.
// Create a new document
app.post('/create', function (req, res) {
const collection = db.collection('mycollection');
collection.insertOne(req.body, function (err, result) {
if (err) throw err;
res.send('Document created');
});
});
// Read existing documents
app.get('/read', function (req, res) {
const collection = db.collection('mycollection');
collection.find({}).toArray(function (err, docs) {
if (err) throw err;
res.send(docs);
});
});
// Update documents
app.put('/update/:id', function (req, res) {
const collection = db.collection('mycollection');
collection.updateOne({ _id: ObjectId(req.params.id) }, { $set: req.body }, function (err, result) {
if (err) throw err;
res.send('Document updated');
});
});
// Delete documents
app.delete('/delete/:id', function (req, res) {
const collection = db.collection('mycollection');
collection.deleteOne({ _id: ObjectId(req.params.id) }, function (err, result) {
if (err) throw err;
res.send('Document deleted');
});
});
With this setup, we now have a basic Node.js application that can perform CRUD operations with a MongoDB database using Express. We can now start building more complex applications and APIs using Node.js, Express, and MongoDB.
Brother Ek crud app react,node,express and mongodb k sath bnao