A Complete Guide - NodeJS CRUD Operations MongoDB
Node.js CRUD Operations with MongoDB
Node.js is a powerful runtime that allows you to build scalable network applications, and MongoDB is a popular NoSQL database known for its flexibility and scalability. Integrating Node.js with MongoDB using the official MongoDB driver or ODMs like Mongoose allows developers to perform CRUD operations efficiently.
1. Setting Up
Before writing CRUD operations, ensure:
- Node.js is installed.
- MongoDB is installed and running.
- The
mongodb
package ormongoose
ODM is installed in your Node.js project.
Install MongoDB Node.js Driver:
npm install mongodb
Install Mongoose ODM:
npm install mongoose
2. Connecting to MongoDB
Using MongoDB Driver: First, establish a connection to MongoDB.
const { MongoClient } = require('mongodb'); async function main() { const uri = "mongodb://localhost:27017"; // Connection String const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { await client.connect(); console.log("Connected successfully to MongoDB."); } finally { await client.close(); }
} main().catch(console.error);
Using Mongoose:
const mongoose = require('mongoose'); async function main() { const uri = "mongodb://localhost:27017"; // Connection String await mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }); console.log("Connected successfully to MongoDB.");
} main().catch(err => console.error(err));
3. Creating a Collection & Schema (Mongoose Only)
Define Mongoose Schema:
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, age: Number, email: String
}); const User = mongoose.model('User', userSchema);
4. CRUD Operations
Create (Insert) Documents:
Using MongoDB Driver:
async function createDoc(client, newDoc) { const result = await client.db("sample_db").collection("users").insertOne(newDoc); console.log(`New document created with the following id: ${result.insertedId}`);
} // Example Document
const newUser = { name: "John Doe", age: 30, email: "john.doe@example.com" };
createDoc(client, newUser).then().catch(console.error);
Using Mongoose:
async function createDoc(userDoc) { const user = new User(userDoc); await user.save(); console.log(`New document created with the following id: ${user._id}`);
} // Example Document
const newUser = { name: "Jane Doe", age: 25, email: "jane.doe@example.com" };
createDoc(newUser).then().catch(console.error);
Read (Find) Documents:
Using MongoDB Driver:
async function findDocs(client, query) { const cursor = client.db("sample_db").collection("users").find(query); const results = await cursor.toArray(); if (results.length > 0) { console.log(`Found documents =>`); results.forEach((doc, index) => console.log(`${index + 1}. ${doc}`)); } else { console.log(`No documents found with the query ${query}`); }
} // Example Query
const query = { age: { $gt: 20 } };
findDocs(client, query).then().catch(console.error);
Using Mongoose:
async function findDocs(query) { const foundDocs = await User.find(query); if (foundDocs.length > 0) { console.log(`Found documents =>`); foundDocs.forEach((doc, index) => console.log(`${index + 1}. ${doc}`)); } else { console.log(`No documents found with the query ${query}`); }
} // Example Query
const query = { age: { $gt: 20 } };
findDocs(query).then().catch(console.error);
Update Documents:
Using MongoDB Driver:
async function updateDoc(client, filter, updateDoc) { const result = await client.db("sample_db").collection("users").updateOne(filter, { $set: updateDoc }); console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`);
} // Example Filter & Update
const filter = { name: "John Doe" };
const updateDoc = { age: 31 };
updateDoc(client, filter, updateDoc).then().catch(console.error);
Using Mongoose:
async function updateDoc(filter, updateDoc) { const result = await User.updateOne(filter, { $set: updateDoc }); console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`);
} // Example Filter & Update
const filter = { email: "jane.doe@example.com" };
const updateDoc = { age: 26 };
updateDoc(filter, updateDoc).then().catch(console.error);
Delete Documents:
Using MongoDB Driver:
async function deleteDoc(client, query) { const result = await client.db("sample_db").collection("users").deleteOne(query); console.log(`${result.deletedCount} document(s) was/were deleted.`);
} // Example Query
const query = { name: "John Doe" };
deleteDoc(client, query).then().catch(console.error);
Using Mongoose:
async function deleteDoc(query) { const result = await User.deleteOne(query); console.log(`${result.deletedCount} document(s) was/were deleted.`);
} // Example Query
const query = { email: "jane.doe@example.com" };
deleteDoc(query).then().catch(console.error);
5. Summary
This guide covered setting up MongoDB with Node.js, creating a basic schema using Mongoose, and performing CRUD operations using both the MongoDB driver and Mongoose ODM. Using these tools effectively can help you build scalable applications that interact with MongoDB seamlessly.
Online Code run
Step-by-Step Guide: How to Implement NodeJS CRUD Operations MongoDB
Prerequisites
Before we begin, ensure you have the following installed:
- Node.js: Download and install from
- npm (Node Package Manager): This usually comes with Node.js.
- Postman: Download and install from mkdir nodejs-crud-api cd nodejs-crud-api npm init -y
Step 2: Install Required Packages
Install Express.js (for handling HTTP requests) and Mongoose (a popular ODM for MongoDB):
npm install express mongoose
Step 3: Create the Basic Server
Create a file named
server.js
and set up a basic Express server.// server.js const express = require('express'); const mongoose = require('mongoose'); // Initialize app const app = express(); // Middleware to parse JSON app.use(express.json()); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true, }); // Check connection mongoose.connection.once('open', () => { console.log('Connected to MongoDB'); }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Step 4: Define Your Mongoose Model
Define a model for the data you want to store in MongoDB.
Create a new file named
models/Item.js
:// models/Item.js const mongoose = require('mongoose'); const itemSchema = new mongoose.Schema({ name: { type: String, required: true }, quantity: { type: Number, required: true }, price: { type: Number, required: true }, }); module.exports = mongoose.model('Item', itemSchema);
Step 5: Create CRUD Routes
Add routes to handle CRUD operations.
Modify
server.js
to include routes:// server.js const express = require('express'); const mongoose = require('mongoose'); const Item = require('./models/Item'); const app = express(); app.use(express.json()); mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true, }); mongoose.connection.once('open', () => { console.log('Connected to MongoDB'); }); // Create a new item app.post('/items', async (req, res) => { try { const item = new Item(req.body); await item.save(); res.status(201).send(item); } catch (error) { res.status(400).send(error); } }); // Get all items app.get('/items', async (req, res) => { try { const items = await Item.find(); res.status(200).send(items); } catch (error) { res.status(500).send(error); } }); // Get an item by ID app.get('/items/:id', async (req, res) => { try { const item = await Item.findById(req.params.id); if (!item) { return res.status(404).send(); } res.status(200).send(item); } catch (error) { res.status(500).send(error); } }); // Update an item by ID app.put('/items/:id', async (req, res) => { try { const item = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }); if (!item) { return res.status(404).send(); } res.status(200).send(item); } catch (error) { res.status(400).send(error); } }); // Delete an item by ID app.delete('/items/:id', async (req, res) => { try { const item = await Item.findByIdAndDelete(req.params.id); if (!item) { return res.status(404).send(); } res.status(200).send(item); } catch (error) { res.status(500).send(error); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Step 6: Test Your API
Start your server:
node server.js
Use Postman to test your API endpoints:
Create an item:
Endpoint:
POST
Body (JSON):
{ "name": "Apple", "quantity": 10, "price": 0.99 }
Get all items:
- Endpoint:
GET
- Endpoint:
Get an item by ID:
- Endpoint:
GET
- Endpoint:
Update an item by ID:
Endpoint:
PUT
Body (JSON):
{ "quantity": 15 }
Delete an item by ID:
- Endpoint:
DELETE
- Endpoint:
Summary
In this tutorial, we covered setting up a basic Node.js application that interacts with a MongoDB database using Mongoose. We defined a model for our data and created routes to handle CRUD operations. Using Postman, we tested these endpoints to ensure they worked as expected.
Top 10 Interview Questions & Answers on NodeJS CRUD Operations MongoDB
1. What is Node.js and MongoDB used for in web development?
Answer: Node.js is a runtime environment for building scalable and high-performance server-side applications using JavaScript. It's lightweight and efficient, thanks to its event-driven architecture. MongoDB, on the other hand, is a NoSQL database that stores data in flexible, JSON-like documents. It’s renowned for its scalability, flexibility, and ease of use. Together, Node.js and MongoDB make an excellent combination for developing modern web applications where data structure might evolve over time or where you need to handle large volumes of data efficiently.
Login to post a comment.