Today’s new knowledge #6(Mongoose)

kishor_sutradhar_d2503ac4

kishor sutradhar

Posted on November 19, 2024

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: 'alice@example.com',
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: 'alice@example.com' }); 
// Finds a specific user

//update
await User.updateOne(
{ email: 'alice@example.com' }, 
{ age: 26 }
);

//delete
await User.deleteOne({ email: 'alice@example.com' });

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: 'example@example.com' });

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 🖐.

💖 💪 🙅 🚩
kishor_sutradhar_d2503ac4
kishor sutradhar

Posted on November 19, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Today’s new knowledge #6(Mongoose)
webdev Today’s new knowledge #6(Mongoose)

November 19, 2024