Logo

dev-resources.site

for different kinds of informations.

Today’s new knowledge #6(Mongoose)

Published at
11/19/2024
Categories
webdev
mongodb
mongoose
beginners
Author
kishor_sutradhar_d2503ac4
Categories
4 categories in total
webdev
open
mongodb
open
mongoose
open
beginners
open
Author
25 person written this
kishor_sutradhar_d2503ac4
open
Today’s new knowledge #6(Mongoose)

Today's Overview:

Hello everyone❤❤❤! Hope you're all doing well. Today, I began exploring Mongoose. With my solid understanding of MongoDB, I felt it was the right time to dive into Mongoose, as it offers a higher-level abstraction for interacting with MongoDB. Here's a summary of what I learned today.

Mongoose

Mongoose is a popular Object Data Modeling (ODM) library for MongoDB and Node.js. It acts as a bridge between your Node.js application and the MongoDB database, enabling you to define data structures and interact with MongoDB in a more structured and efficient way. when you send data to MongoDB, mongoose maps the data with the model, and if the data matches the model structure then with the help of the MongoDB driver the data is sent to mongoDB. so it ensures the validity of the data.

Why should we use Mongoose?

  • Schema Definition
  • Model Creation
  • Data Validation
  • Querying
  • Middleware Support
  • Population of reference data

Connecting to MongoDB

Mongoose establishes a connection to the MongoDB database using a URI. Once connected, it provides methods to interact with the database.

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydatabase')
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Connection error:', err));

Enter fullscreen mode Exit fullscreen mode

Schemas:

A schema in Mongoose is a blueprint that defines the structure, data types, default values, and validation rules for documents in a MongoDB collection. It ensures data consistency and makes working with MongoDB collections more structured.

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: { type: String, required: true },       
// Required field of type String
    email: { type: String, required: true },      
// Required and must be unique
    age: { type: Number, min: 0 },                
// Number with minimum value validation
    isAdmin: { type: Boolean, default: false },   
// Default value if not provided
    createdAt: { type: Date, default: Date.now }  
// Automatically sets the current date
});
Enter fullscreen mode Exit fullscreen mode

Common Schema Properties

type: Specifies the data type (String, Number, Boolean, Date, Buffer, ObjectId, Array, etc.).
required: Ensures the field must be provided.
default: Sets a default value if none is provided.
unique: Ensures the value in the field is unique across documents.
enum: Specifies allowed values for a field.
validate: Provides custom validation logic.

Model

In Mongoose, a model is a class that provides an interface to interact with a specific MongoDB collection.

const User = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode

CRUD Operations

Mongoose simplifies operations like creating, reading, updating, and deleting documents. Here's how:

//create
const newUser = new User({ 
name: 'Alice',
email: '[email protected]',
age: 25 
});
await newUser.save(); 
// Saves the document to MongoDB

//read
const users = await User.find(); 
// Retrieves all users
const user = await User.findOne({ email: '[email protected]' }); 
// Finds a specific user

//update
await User.updateOne(
{ email: '[email protected]' }, 
{ age: 26 }
);

//delete
await User.deleteOne({ email: '[email protected]' });

Enter fullscreen mode Exit fullscreen mode

Relationships (Population)

In Mongoose, population is a feature that enables you to work with relationships between documents stored in different collections.

const postSchema = new mongoose.Schema({
    title: String,
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});
const Post = mongoose.model('Post', postSchema);

// Populate author details when querying posts
const posts = await Post.find().populate('author');
Enter fullscreen mode Exit fullscreen mode

Validation

Mongoose provides robust built-in validation to ensure data integrity before it is saved to the database. You can define validation rules directly in the schema to enforce constraints like required fields, value ranges, custom checks, and more.

const userSchema = new mongoose.Schema({
    name: { type: String, required: true }, 
// Name is mandatory
    email: { type: String, required: [true, 'Email is required'], match: /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/ } 
// Custom error message and regex validation
price: { type: Number, min: 0, max: 1000 } 
// Price must be between 0 and 1000
});
title: { type: String, minlength: 5, maxlength: 100 }
 // Title length must be 5–100 characters

 age: {
        type: Number,
        validate: {
            validator: function (value) {
                return value >= 18; 
                 // Age must be at least 18
            },
            message: 'Age must be 18 or older' 
            // Custom error message
        }
    }
});
//custom validation
Enter fullscreen mode Exit fullscreen mode

Query Building

Mongoose provides a powerful, chainable API to construct and execute database queries with ease. Queries are built using query objects, which allow you to filter, project, sort, and paginate data.

const users = await User.find({ age: { $gte: 18 } });

const user = await User.findOne({ email: '[email protected]' });

const user = await User.findById('648e5f2a7a1b2c6d4e5f3a4d');
Enter fullscreen mode Exit fullscreen mode

Query Chain

Mongoose queries are chainable, meaning you can combine filters, projections, and options.

const users = await User.find({ age: { $gte: 18 } }) // Filter users by age
    .select('name email')                          // Project only 'name' and 'email' fields
    .sort({ name: 1 })                             // Sort by name in ascending order
    .limit(10);                                    // Limit to 10 results

Enter fullscreen mode Exit fullscreen mode

*note: * For advanced data processing, use the MongoDB Aggregation Framework via Mongoose.

Conclusion:

That's all I learned today about mongoose. I also practice other things that I learned previously. Hope to talk to you soon. Bye Bye 🖐.

mongoose Article's
30 articles in total
Favicon
Crudify: Automate Your Mongoose CRUD Operations in NestJS
Favicon
6 Steps to Set Up MongoDB Atlas for Node.js Applications
Favicon
Mysql 101 for Mongoose developer.
Favicon
Tutorial de Instalação: Express com MongoDB e Mongoose
Favicon
Today’s new knowledge #6(Mongoose)
Favicon
Today’s new knowledge #10 (Building a Flexible Query Builder for MongoDB with Mongoose)
Favicon
mongoose connect to express
Favicon
I Fumbled on a Next.js MongoDB Error and Learned the Key Differences Between Mongoose and MongoClient
Favicon
Setup Eslint Prettier in a TypeScript project with mongoose ODM
Favicon
Bootcamping 01: An Unexpected Behavior of Mongoose
Favicon
Common Myths About Mongoose
Favicon
5 Quick And Easy MongoDB Optimizations (part 1)
Favicon
Mongoose Interview Questions
Favicon
MongoDB vs. Mongoose: Understanding Their Roles and Differences
Favicon
We finally have a fullstack framework for MongoDB
Favicon
Mongoose
Favicon
💬 Building a Real-time Chat Feature for Virtual Gift Store Using Socket.IO with MERN Stack 🚀
Favicon
The Power of exec() in Mongoose: Unlocking Better Query Execution
Favicon
Enhancing Mongoose Reference Handling in Node.js
Favicon
Mongoose Documentation
Favicon
How to Connect MongoDB with Node.js: A Comprehensive Guide
Favicon
Updating Non-Primitive Data in an Array Using Transactions and Rollbacks
Favicon
Method Chaining in Mongoose: A Brief Overview
Favicon
Understanding Transactions and Rollbacks in MongoDB
Favicon
Understanding Populating Referencing Fields in Mongoose
Favicon
How to Use Bcrypt for Password Hashing in Node.js
Favicon
Getting Started with Mongoose
Favicon
Running Unit Tests with MongoDB in a Node.js Express Application using Jest
Favicon
Setting up MongoDB using Mongoose in Node.js
Favicon
I built an open-source schema visualisation tool for mongoose

Featured ones: