In Express.js, a popular framework for building web applications with Node.js, integrating with databases is a common requirement. Mongoose, an Object Data Modeling (ODM) library, simplifies this process when working with MongoDB. In this article, we’ll explore how to fetch data using Mongoose in an Express application.
To begin, let’s take a look at the code snippet below:
const express = require('express');
const router = express.Router();
const Product = require('../models/Product');
// Get all products
router.get('/products', async (req, res) => {
try {
const products = await Product.find();
res.json(products);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
module.exports = router;
In this code, we have an Express router that handles a GET request to the /products endpoint. Within the route handler, we utilize Mongoose to fetch data from the MongoDB database.
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
price: { type: Number, required: true }
});
module.exports = mongoose.model('Product', productSchema);
The Product model, which represents the MongoDB collection, is imported from the ../models/Product file. The model is defined using the mongoose.Schema function, specifying the fields of the documents it will store. In this case, the name and price fields are required.
To fetch the data, the code uses the Product.find() function, provided by Mongoose. This function retrieves all documents from the Product collection. It returns a Promise that resolves to an array of documents matching the query criteria.
Upon a successful fetch, the retrieved products are sent as a JSON response using res.json(products). In case of an error during the database operation, the code responds with a 500 Internal Server Error and an error message using res.status(500).json({ error: 'Internal server error' }).
These Mongoose functions play a crucial role in interacting with the database. Here’s a summary of their usage:
mongoose.Schema: Defines the structure of documents in a MongoDB collection.
mongoose.model: Creates a model based on a defined schema, enabling CRUD operations.
Model.find(): Retrieves documents from the database based on query criteria.
res.json(): Sends a JSON response to the client.
res.status(): Sets the HTTP response status code.
res.json(): Sends a JSON response to the client.
By combining Express and Mongoose, fetching data from a MongoDB database becomes a streamlined process. You can build powerful and efficient applications by leveraging the capabilities of these frameworks.
In conclusion, we’ve explored how to fetch data using Mongoose in an Express application. With a clear understanding of these functions, you