Getting Started with MongoDB and Mongoose - A Comprehensive Guide

Author avatar

Karan Salvi / June 6, 2025

Getting Started with MongoDB and Mongoose - A Comprehensive Guide

Getting Started with MongoDB and Mongoose

MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. Mongoose is an elegant MongoDB object modeling tool for Node.js.


๐Ÿƒ Why Use MongoDB?

  • ๐Ÿงพ Schema-less and flexible
  • ๐Ÿš€ High performance and scalability
  • ๐Ÿ”„ Easily handles large volumes of unstructured data
  • ๐Ÿ” Built-in replication and sharding support

๐Ÿงฐ Why Use Mongoose?

Mongoose adds structure and convenience on top of MongoDB:

  • โœ… Schema definitions
  • ๐Ÿ”’ Data validation
  • ๐Ÿ” Middleware support (pre/post hooks)
  • ๐Ÿงฉ Simple API for querying and updating documents

๐Ÿ”ง Installing MongoDB and Mongoose

npm install mongoose

Make sure you have MongoDB installed and running locally or use MongoDB Atlas.


๐ŸŒ Connecting to MongoDB

// db.js
const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/myapp", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
  console.log("Connected to MongoDB");
});

๐Ÿงฑ Defining a Schema and Model

// models/User.js
const mongoose = require("mongoose");

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

const User = mongoose.model("User", userSchema);
module.exports = User;

๐Ÿ“ฆ Creating and Saving Documents

const User = require("./models/User");

const newUser = new User({
  name: "Alice",
  email: "alice@example.com",
  age: 25,
});

newUser
  .save()
  .then((user) => console.log("User saved:", user))
  .catch((err) => console.error(err));

๐Ÿ” Querying Documents

User.find().then((users) => console.log(users));

User.findOne({ email: "alice@example.com" }).then((user) => console.log(user));

User.findById("someId").then((user) => console.log(user));

โœ๏ธ Updating Documents

User.updateOne({ email: "alice@example.com" }, { age: 30 }).then((result) =>
  console.log(result)
);

User.findByIdAndUpdate("someId", { name: "Alice Updated" }, { new: true }).then(
  (updated) => console.log(updated)
);

โŒ Deleting Documents

User.deleteOne({ email: "alice@example.com" }).then((result) =>
  console.log(result)
);

User.findByIdAndDelete("someId").then((deleted) => console.log(deleted));

โš™๏ธ Schema Validation and Defaults

Mongoose allows built-in validation:

const productSchema = new mongoose.Schema({
  name: { type: String, required: true },
  price: { type: Number, min: 0 },
  inStock: { type: Boolean, default: true },
});

๐Ÿง  Middleware (Hooks)

Pre-save hook example:

userSchema.pre("save", function (next) {
  this.name = this.name.trim();
  next();
});

๐Ÿ”— Relationships (References)

const blogPostSchema = new mongoose.Schema({
  title: String,
  body: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
});

const BlogPost = mongoose.model("BlogPost", blogPostSchema);

BlogPost.find()
  .populate("author")
  .then((posts) => console.log(posts));

๐Ÿ›ก๏ธ Indexes and Performance

userSchema.index({ email: 1 });

๐Ÿงช Testing with MongoDB Memory Server

npm install --save-dev mongodb-memory-server

Use in tests:

const { MongoMemoryServer } = require("mongodb-memory-server");

๐Ÿ“ Project Structure Example

src/
โ”‚
โ”œโ”€โ”€ models/
โ”‚   โ””โ”€โ”€ User.js
โ”œโ”€โ”€ db.js
โ”œโ”€โ”€ app.js
โ””โ”€โ”€ routes/
    โ””โ”€โ”€ userRoutes.js