Introduction to Mongoose | Manvi Sharma

Post

editor-img
Manvi Sharma
May 27, 2023

Introduction to Mongoose

Hi everyone,

Today we will learn about Mongoose.

An Object Data Modeling(ODM) library for Node.js and MongoDB which provides a higher-level abstraction for interacting with MongoDB, a popular NoSQL database and simplifies the process of defining and working with data models and schemas.

Key Features of Mongoose:

Schema Definition: Mongoose allows you to define data schemas that act as blueprints for your data models. Schemas define the structure, validation rules, and relationships between data fields, providing a consistent and organized way to work with your data.

export interface UserDocument extends mongoose.Document { email: string; password: string; name: string; isVerified: boolean;}

Model Creation: Using Mongoose, you can create models based on the defined schemas. Models represent collections in MongoDB and provide an interface to interact with the database. They enable you to perform CRUD operations (Create, Read, Update, Delete) on your data with ease.

export const User = mongoose.model<UserDocument, UserModelStatic>( "User", userSchema);

Data Validation: Mongoose offers robust validation capabilities for your data. You can specify validation rules for each field in the schema, such as data type checks, required fields, custom validators, and more. Mongoose automatically validates the data before saving it to the database, ensuring data integrity and consistency.

const userSchema = new mongoose.Schema( { name: { type: String, required: true, trim: true, }, email: { type: String, unique: true, required: true, trim: true, lowercase: true, validate(value) { if (!validator.isEmail(value)) { throw new Error('Email is invalid') } }, }, age: { type: Number, default: 0, validate(value) { if (value < 0) { throw new Error('Age must be greater than equal to 0.') } }, }, password: { type: String, required: true, trim: true, minlength: 7, validate(value) { if (R.includes('password', R.toLower(value))) { throw new Error("Password must not contain string 'password'") } }, })

Query Building: Mongoose simplifies the process of constructing database queries. It provides a fluent API for building queries, allowing you to perform complex operations like filtering, sorting, pagination, and aggregation using a simple and intuitive syntax.

const userVerified = await User.findOneAndUpdate( { _id: decodedEmailToken._id }, { isVerified: true }, { new: true, } );

The query above finds a user on the basis of id and updates the verification status for the user. The findOneAndUpdate API is self-explanatory

Data Population: Mongoose facilitates data population, which allows you to automatically replace references to other documents with the actual document data. This feature simplifies working with relationships between collections and makes retrieving and displaying related data easier.

Indexing and Performance Optimization: Mongoose provides an intuitive way to define indexes on your schema fields. Indexes enhance query performance by allowing faster data retrieval based on the indexed fields. Mongoose also offers various optimization techniques and configuration options to improve overall application performance.

Integration with Express and Node.js Ecosystem: Mongoose seamlessly integrates with the Express framework and the broader Node.js ecosystem. It provides a bridge between your application's business logic and the MongoDB database, allowing you to focus on writing clean, modular, and maintainable code.

Middleware and Hooks: Mongoose supports middleware, also known as hooks, which allow you to intercept and modify various operations during the document's lifecycle. You can define pre and post-hooks for events such as saving, validating, removing, and more. Middleware enables you to execute custom logic and perform additional operations before or after these events.

// HASH PLAIN TEXT PASSWORDuserSchema.pre("save", async function (next) { const user = this; if (user.isModified("password")) { user.password = await bcrypt.hash(user.password, 8); } next();});

userSchema.methods.generateToken = function () { const user = this; const token = jwt.sign( { _id: user._id?.toString(), name: user.name }, process.env.JWT_SECRET as string, { expiresIn: "4 days", } ); return token;};

By leveraging Mongoose's features, we can simplify database interactions, ensure data consistency, and enhance the development process of MongoDB-backed applications in Node.js.

That is all for today, but in the coming posts, we will explore the various features of Mongoose in detail, especially middleware and hooks with some practical examples and explanations, for using Mongoose effectively and building robust, scalable Node.js applications with MongoDB integration.


Checkout related posts on: