What is mongoose & its key features
Updated: May 3, 2023
![](https://static.wixstatic.com/media/11062b_b0df5d06c30e47a0a1afd4a79aa8c1ac~mv2.jpg/v1/fill/w_980,h_705,al_c,q_85,usm_0.66_1.00_0.01,enc_auto/11062b_b0df5d06c30e47a0a1afd4a79aa8c1ac~mv2.jpg)
Mongoose is an Object-Document Mapping (ODM) library for Node.js and MongoDB. It provides a simple and efficient way to interact with MongoDB from Node.js applications. With Mongoose, you can define data models using a schema which provides a clear structure and built-in validation rules for your data that allows you to validate data before saving it to the database and then perform various operations on those models, such as creating, reading, updating, and deleting data in the MongoDB database.
Define data models using a schema (Schema-based data modeling)
const mongoose = require("mongoose");
const contactSchema = mongoose.Schema({
name:{
type:String,
required: [true, "Name can't be null"]
},
email:{
type:String,
required: [true, "Email can't be null"]
},
phone:{
type:String,
required: [true, "Phone can't be null"]
},
}, {
timestamps: true,
})
module.exports = mongoose.model("Contact", contactSchema); |
mongoose provides additional features and functionalities such as schema validation, middleware, query building, and more as it is built on top of the official MongoDB Node.js driver . It is widely used in Node.js applications that use MongoDB as the underlying database, as it simplifies the development process and makes it easier to work with MongoDB data.
Making the Connection with MongoDB with mongoose
const mongoose = require ("mongoose");
const connectDb = async () => {
try {
const connect = await mongoose.connect(process.env.CONNECTION_STRING);
console.log("DB Connected", connect.connection.host, connect.connection.name);
} catch(err) {
console.log(err);
process.exit(1);
}
};
module.exports = connectDb; |
Controller to handle requests for different routes in the application
A a controller is a module in Node.js application that requests and responses from the client which helps us to separate concerns and build scalable applications. Controllers can manipulate data from the database or other sources to prepare it for presentation to the client. Controllers can implement business logic specific to the application, such as authentication, authorization, and validation.Controllers can act as middleware in the request-response cycle, performing tasks such as parsing request bodies, handling errors, and sending responses.
In the code given below, handles requests for different routes in the application. For example, if a user makes a GET request to "/contacts", the ContactController can handle the request and return a list of contacts.
const asyncHandler = require("express-async-handler");
const Contact = require("../models/contactModel");
//@desc Get all contacts
//@route GET /api/contacts
//@access public
const getContacts = asyncHandler(async (req, res) => {
const contacts = await Contact.find();
res.status(200).json(contacts);
});
//@desc Create new contact
//@route POST /api/contacts
//@access public
const createContact = asyncHandler(async (req, res) => {
const {name, email, phone} = req.body;
if(!name || !email || !phone) {
res.status(400);
throw new Error("All Fileds Are Mandatory!");
}
const contact = await Contact.create({
name,
email,
phone,
})
res.status(200).json(contact);
});
//@desc Get contact
//@route GET /api/contacts/:id
//@access public
const getContact = asyncHandler(async (req, res) => {
const contact = await Contact.findById(req.params.id);
if(!contact){
res.status(404);
throw new Error("Contact Not Found!");
}
res.status(200).json(contact);
});
//@desc Update contact
//@route PUT /api/contacts/:id
//@access public
const updateContact = asyncHandler(async (req, res) => {
const contact = await Contact.findById(req.params.id);
if(!contact){
res.status(404);
throw new Error("Contact Not Found!");
}
const updatedContact = await Contact.findByIdAndUpdate(
req.params.id,
req.body,
{new: true}
)
res.status(200).json(updatedContact);
});
//@desc Delete contact
//@route DELETE /api/contacts/:id
//@access public
const deleteContact = asyncHandler(async (req, res) => {
const contact = await Contact.findById(req.params.id);
if(!contact){
res.status(404);
throw new Error("Contact Not Found!");
}
await Contact.findByIdAndRemove(req.params.id);
res.status(200).json({message:`Contact is deleted for ${req.params.id}`});
});
module.exports= { getContacts,
createContact,
getContact,
updateContact,
deleteContact}; |
Comments