Day 33 of #100DaysOfCode — Mongoose

Published: (March 6, 2026 at 08:45 PM EST)
3 min read
Source: Dev.to

Source: Dev.to

Introduction

Databases can store any amount or type of data, but they usually don’t enforce a strict structure by default.
MongoDB is schema‑less, meaning it doesn’t enforce strict structure. To maintain structure, validation, and consistency, developers use Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js.

Why Mongoose?

  • Provides schemas, validation, and models.
  • Acts as a layer between Node.js and MongoDB, making large applications cleaner, safer, and easier to maintain.
  • Offers middleware support, default values, and required‑field enforcement.

Without Mongoose

// raw MongoDB driver
const db = client.db("MyDatabase");
await db.collection("users").insertOne({ name: "Saad", age: 25 });
const users = await db.collection("users").find().toArray();
  • No validation → garbage data can be inserted.
  • No consistent structure → queries vary across developers.
  • No hooks → repetitive tasks (e.g., password hashing) must be handled manually.

With Mongoose

await User.create({ name: "Saad", age: 25 });

Mongoose provides clean, structured, and validated interactions.

Installing Mongoose

npm install mongoose

Basic Import & Connection

const mongoose = require("mongoose");

const uri = "mongodb://127.0.0.1:27017/testdb";

async function run() {
  await mongoose.connect(uri);
  console.log("Connected");

  // ... your code ...

  await mongoose.disconnect();
}

run().catch(console.error);

Defining a Schema

A Schema defines the structure of documents inside a MongoDB collection.

const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  isWorking: Boolean,
});

Advanced Schema Example (validation, defaults)

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  age: Number,
  email: { type: String, required: true },
  createdAt: { type: Date, default: Date.now },
  skills: [String],
});

Schemas help define:

  • Field types
  • Arrays & nested objects
  • Required fields
  • Default values

Creating a Model

A Model is the interface used to interact with a collection.

const User = mongoose.model("User", userSchema); // collection: users

CRUD Operations with Mongoose

// Create
await User.create({ name: "Saad", age: 26, isWorking: false });

// Read
const users = await User.find();               // all users
const user = await User.findOne({ name: "Saad" });
const filtered = await User.find({ age: { $gt: 20 } });

// Update
await User.updateOne({ name: "Saad" }, { age: 24 });

// Delete
await User.deleteOne({ name: "Saad" });

Comparison with raw MongoDB queries

// MongoDB
db.users.find({ age: { $gt: 20 } });

// Mongoose
User.find({ age: { $gt: 20 } });

Both are similar, but Mongoose returns JavaScript objects that respect the defined schema.

Key Concepts

  • MongoDB URI – connection string for the database.
  • Connection promisemongoose.connect() returns a promise.
  • Error handling – use .catch() or try/catch around async calls.

Conclusion

Mongoose adds structure and rules on top of MongoDB, enabling developers to manage data more safely and efficiently in Node.js applications. It provides schemas, validation, middleware, and a clean API for CRUD operations, turning a schema‑less database into a well‑organized data layer.

0 views
Back to Blog

Related posts

Read more »