How to use Postman to Interact with MongoDB Data In NodeJS
Let’s create an endpoint to retrieve users from our database and test it using Postman.
1. Create an Express Route
app.get('/books', async (req, res) => {
try {
// Fetch all books from the database
const books = await Book.find();
res.json(books); // Respond with the list of books as JSON
} catch (err) {
console.error('Error fetching books:', err);
res.status(500).json({ message: 'Internal Server Error' });
}
});
2. Testing with Postman
- Start your server (node server.js).
- Open Postman and make a GET request to http://localhost:8800/books.
- You should receive a JSON response with the users stored in your MongoDB database.
This URL corresponds to the route you defined in your Express application to fetch all books (/books).
Example: Below is a an example to Use MongoDB and Mongoose with Node.js.
const express = require('express');
const mongoose = require('mongoose');
const Book = require('./models/book.js');
// Create Express app
const app = express();
// Middleware to parse JSON bodies
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase')
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err) => {
console.error('Error connecting to MongoDB:', err);
});
// Insert books into the database
const books = [
{
title: "The Catcher in the Rye",
author: "J.D. Salinger",
year: 1951
},
{
title: "To Kill a Mockingbird",
author: "Harper Lee",
year: 1960
},
{
title: "1984",
author: "George Orwell",
year: 1949
},
{
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925
},
{
title: "Pride and Prejudice",
author: "Jane Austen",
year: 1813
}
];
// Insert multiple documents (books) into the collection
Book.insertMany(books)
.then(() => {
console.log('Books inserted successfully');
})
.catch((err) => {
console.error('Error inserting books:', err);
});
// Route to fetch all books
app.get('/books', async (req, res) => {
try {
// Fetch all books from the database
const books = await Book.find();
res.json(books); // Respond with the list of books as JSON
} catch (err) {
console.error('Error fetching books:', err);
res.status(500).json({ message: 'Internal Server Error' });
}
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
const mongoose = require('mongoose');
const bookSchema = new mongoose.Schema({
title: String,
author: String,
year: Number
});
const Book = mongoose.model('Book', bookSchema);
module.exports = Book;
Output:
How to Use MongoDB and Mongoose with Node.js ?
In the world of Node.js development, MongoDB is a popular choice for database management due to its flexibility and scalability. When working with MongoDB in a Node.js environment, using Mongoose—a JavaScript library—makes the interaction with the database even more efficient and structured. In this article, we’ll explore how to integrate MongoDB and Mongoose into a Node.js application step by step.
Table of Content
- What is Mongoose?
- Steps to Create the NodeJS App And Installing Module
- Establish Mongoose MongoDB Node.js Connection
- Model a Schema using Mongoose
- Add Data to the Database using the Mongoose Schema
- Using Postman to Interact with MongoDB Data
- Conclusion