Filtering MongoDB Documents by ID in Node.js with Express.js
Last Updated :
28 May, 2024
Filtering is a very basic feature that an API must possess to serve data to the client application efficiently. By handling these operations on the server side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance. In this article, we are going to learn how to filter data from MongoDB by using NodeJs and ExpressJs.
Approach to Filter MongoDB Documents by ID with Express.js
To filter MongoDB documents by ID in a Node.js application using Express.js
- you first set up route parameters to capture the ID from the URL in your route definitions.
- In the
ItemRoutes.js
file, define a route that includes /:id
extracting the document ID from incoming requests. Within the route handler, use Mongoose's findById
method to query the MongoDB database for the document with the specified ID. - After retrieving the document, check if it exists: if the document is found, respond with the document's data; if not, return a 404 status with an appropriate error message.
- Handle any potential server errors with a try-catch block, ensuring the server responds with a 500 status code and a server error message in case of failure.
- This approach ensures that your application can accurately filter and return MongoDB documents based on their IDs, providing meaningful responses to clients.
Steps to Create a NodeJS App and Installing Modules
Step 1: First, we’ve to initialize a new project using Node Package Manager. We can complete the setup by selecting all the default options.
npm init -y
Step 2:. Next, we’ve to install the express package.
npm install express mongoose
Step 3: Create server.js file in your root directory by following command in terminal.
mkdir server.js
Step 4: Create a folder model inside model folder create a file Item.js.
mkdir model
cd model
touch Item.js
Step 5: Create a folder route in root directory inside route create a file ItemRoutes.js
mkdir route
cd route
touch ItemRoutes.js
Project Structure:
.png)
The Updated dependency in your package.json file is looks like:
"dependencies": {
"express": "^4.19.2",
"mongoose": "^8.4.0"
}
Example: Below is an example to Filter MongoDB Documents by ID in Node.js with Express.js:
JavaScript
// server.js
const express = require("express");
const mongoose = require("mongoose");
const ItemRoutes = require("./routes/ItemRoutes")
const Item = require("./model/Item");
const app = express();
const PORT = process.env.PORT || 3000;
app.get("/", ItemRoutes);
app.get("/:id", ItemRoutes);
mongoose
.connect("mongodb://localhost:27017/myapp")
.then(() => {
console.log("Connected to MongoDB");
insertData();
})
.catch((err) => {
console.error("Error connecting to MongoDB", err);
});
const insertData = async () => {
await Item.deleteMany();
let data = [
{
name: "Item 1",
description: "Description of item 1",
},
{
name: "Item 2",
description: "Description of item 2",
},
{
name: "Item 3",
description: "Description of item 3",
},
];
await Item.insertMany(data);
console.log("Data inserted");
}
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
JavaScript
// model/itemSchema.js
const mongoose = require("mongoose");
const itemSchema = new mongoose.Schema({
name: String,
description: String,
// Add more fields as needed
});
module.exports = mongoose.model("Item", itemSchema);
JavaScript
// routes/ItemRoutes.js
const express = require("express");
const router = express.Router();
const Item = require("../model/Item");
router.get("/", async (req, res) => {
try {
const item = await Item.find({});
if (!item) {
return res.status(404).json({
message: "Item not found"
});
}
res.json(item);
} catch (err) {
console.error(err);
res.status(500).json({
message: "Server Error"
});
}
})
// Get item by ID
router.get("/:id", async (req, res) => {
console.log(req.params.id);
try {
const item = await Item.findById(req.params.id);
if (!item) {
return res.status(404).json({
message: "Item not found"
});
}
res.json(item);
} catch (err) {
console.error(err);
res.status(500).json({
message: "Server Error"
});
}
});
module.exports = router;
Steps to run:
1. Run this command in your terminal.
node server.js
2. Enter this url in your browser
localhost:3000
Output:
Filtering MongoDB Documents by ID in Node.js with Express.js
Filtering MongoDB Documents by ID in Node.js with Express.js
Similar Reads
How to Find Documents by ID in MongoDB?
In MongoDB, finding documents by their unique identifier (ID) is a fundamental operation that allows us to retrieve specific records efficiently. Each document in a MongoDB collection has a unique _id field, which serves as the primary key. In this article, we will explore how to find documents by I
3 min read
How to Implement Search and Filtering in a REST API with Node.js and Express.js ?
Search and filtering are very basic features that an API must possess to serve data to the client application efficiently. By handling these operations on the server-side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance.In this
5 min read
How to find all the document keys of MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
1 min read
How to Get the id of Inserted Document in MongoDB in NodeJS
MongoDB is a popular type of NoSQL database. It stores data in documents that look like JSON. When working with MongoDB using Mongoose, _id is a unique identifier of each document in a collection and it can be used to perform operations on the document, such as updating or deleting it. The insertion
5 min read
How to limit the number of documents in a MongoDB request in Node.js ?
Say you are working on a quiz API, with which anybody on the web can fetch random questions based on the defined category. You are done with your API and it has passed all test parameters, now for sake of users you want to add a feature that will let users decide how many questions they want to addr
5 min read
How to insert single and multiple documents in Mongodb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
How to get Distinct Documents from MongoDB using Node.js ?
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. MongoDB module: This module of Node.js is used for connecting the Mongo
2 min read
File Sharing Platform with Node.js and Express.js
In today's digital age, the need for efficient File sharing platforms has become increasingly prevalent. Whether it's sharing documents for collaboration or distributing media files, having a reliable solution can greatly enhance productivity and convenience. In this article, we'll explore how to cr
4 min read
Working with forms using Express.js in Node.js
In this article, we will be working with forms using ExpressJS in NodeJS.Using server side programming in Node.js, we can create forms where we can put certain parameters which upon filling gets stored in the database.Setting up environment:You can refer to this website for downloading Node.js. Alon
3 min read
How To Query For Documents In MongoDB Using NodeJS?
MongoDB is the popular NoSQL database that allows for flexible and scalable data storage. NodeJS and JavaScript runtime built on Chrome's V8 JavaScript engine. It is often used with MongoDB to build powerful and efficient applications. In this article, we will guide you on how to query the documents
4 min read