Understanding Mongoose Model Classes in Node.js

Photo by Rubaitul Azad on Unsplash

Introduction

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. One of the most crucial aspects of Mongoose is the Model, which provides a straightforward, schema-based solution to model your application data.

What is a Mongoose Model?

A Mongoose Model is essentially a constructor compiled from a Schema definition. An instance of a model represents a MongoDB document and can be saved, queried, updated, and deleted.

Creating a Mongoose Model

To create a Mongoose Model, you use the .model method, which takes two primary arguments:

  1. The name of the collection
  2. The schema defining the structure of documents within that collection

Here’s a simple example:

import mongoose, { Schema, Document } from "mongoose";

interface IUser extends Document {
username: string;
email: string;
}

const UserSchema: Schema = new Schema({
username: { type: String, required: true },
email: { type: String, required: true },
});

const User = mongoose.model<IUser>("User", UserSchema);

In this example, we define a User model with a corresponding schema, UserSchema.

Boot-up Behavior

When your application boots up, Mongoose checks if the collection already exists in MongoDB. If it does, Mongoose will not create a new one. This is advantageous because it prevents accidental overwrites or duplications.

Operations Using Model Instances

Once you have a model, you can perform various CRUD operations. Below are examples for each:

Create

const newUser = new User({
username: "JohnDoe",
email: "john.doe@example.com",
});

await newUser.save();

Read

const user = await User.findOne({ username: "JohnDoe" });

Update

await User.updateOne({ username: "JohnDoe" }, { email: "new.email@example.com" });

Delete

await User.deleteOne({ username: "JohnDoe" });

Conclusion

Understanding Mongoose Models is crucial for working efficiently with MongoDB in a Node.js environment. A Mongoose Model serves as a compiled version of a schema and acts as a constructor for creating new documents.

,