Databases can store any amount or type of data, but they usually don't enforce a strict structure by default. Especially with NoSQL databases like MongoDB, developers can insert documents with different fields or data types.
To maintain structure, validation, and consistency, we use something called Mongoose.
Day 33 was all about what Mongoose is, why it exists, and how it helps manage data in Node.js applications.
TL;DR
- MongoDB is schema-less, meaning it doesn't enforce strict structure.
- Mongoose provides schemas, validation, and models.
- It acts as a layer between Node.js and MongoDB.
- It makes large applications cleaner, safer, and easier to maintain.
What is Mongoose
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.
It provides a schema-based solution to model application data, even though MongoDB itself is schema-less.
In simple terms:
Mongoose adds structure and rules on top of MongoDB so developers can manage data more safely and easily.
What Does Mongoose Provide?
Mongoose = ODM (Object Data Modeling) Library
It provides:
- Schema structure for MongoDB documents
- Data validation
- Easy CRUD operations
- Middleware support
- Cleaner code for backend apps
Without Mongoose:
db.users.insertOne({...})
With Mongoose:
User.create({...})
So it acts as a layer between Node.js and MongoDB.
Why Even Need Mongoose in the First Place?
Without Mongoose, talking to MongoDB looks like this:
// 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();
It works, but as your app grows:
- No validation — anyone can insert garbage data
- No structure — every developer writes queries differently
- No hooks — you manually handle things like password hashing every time
- Gets messy and hard to maintain very quickly
With Mongoose:
// Clean, structured, validated
await User.create({ name: "Saad", age: 25 });
Think of raw MongoDB like cooking from scratch every single day — you can do it, but it's exhausting.
Mongoose is like having a meal prep system — structured, consistent, saves you time, prevents mistakes.
Working with Mongoose
Install:
npm install mongoose
Basic import:
const mongoose = require("mongoose");
Connecting to MongoDB
const { MongoClient, ServerApiVersion } = require("mongodb");
const mongoose = require("mongoose")
const uri =
"mongodb://127.0.0.1:27017/testdb";
const userSchema = new mongoose.Schema({
name: String,
age: Number,
isWorking: Boolean,
})
const user = mongoose.model("User", userSchema)
async function run() {
await mongoose.connect(uri)
console.log("Connected");
await user.create({ name: "Saad", age: 26, isWorking: false})
const users = await user.find()
console.log(users);
await mongoose.disconnect()
}
run().catch(console.error)
Concepts to understand here:
- MongoDB URI
- connection promise
- error handling
Understanding Schemas in Mongoose
A Schema defines the structure of documents inside a MongoDB collection.
Example:
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
skills: [String]
});
Schemas help define:
- field types
- arrays
- nested objects
- required fields
- default values
Example with validation:
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
email: { type: String, required: true },
createdAt: { type: Date, default: Date.now }
});
Now MongoDB will reject documents that don't follow this structure.
Models in Mongoose
A Model is the interface used to interact with a collection in MongoDB.
const User = mongoose.model("User", userSchema);
This automatically creates a collection named:
users
Now you can do operations like:
User.find()
User.create()
User.updateOne()
CRUD Operations with Mongoose
Create
await User.create({
name: "Saad",
age: 23
});
Read
const users = await User.find();
const user = await User.findOne({ name: "Saad" });
Update
await User.updateOne(
{ name: "Saad" },
{ age: 24 }
);
Delete
await User.deleteOne({ name: "Saad" });
Mongoose vs MongoDB Query Differences
MongoDB:
db.users.find({ age: { $gt: 20 } })
Mongoose:
User.find({ age: { $gt: 20 } })
Very similar, but integrated with JS objects.
Wrap up
Databases like MongoDB can store almost any type of data, but to ensure correct structure and consistent data, developers use Mongoose.
It provides schemas, validation, and cleaner database interaction for Node.js backend applications.
Thanks for reading. Feel free to share your thoughts!
Top comments (0)