Tutorials Logic, IN info@tutorialslogic.com

Mongoose ODM Schema, Models, CRUD: Tutorial, Examples, FAQs & Interview Tips

Mongoose ODM Schema, Models, CRUD

Mongoose in MongoDB is best learned by connecting the rule to a product catalog or user activity store. Start with the smallest collection query, observe the output, and then add one realistic constraint so the concept becomes practical.

The key habit for this lesson is to watch document shape and index as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.

What is Mongoose?

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a schema-based solution to model your application data, with built-in type casting, validation, query building, and business logic hooks. Think of it as an ORM for MongoDB.

Installation and Connection

Installing Mongoose and Connecting

Installing Mongoose and Connecting
// Install Mongoose
npm install mongoose

// Connect to MongoDB
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 via Mongoose!")
})

// Or using async/await
async function connectDB() {
  try {
    await mongoose.connect("mongodb+srv://user:pass@cluster0.abc123.mongodb.net/myapp")
    console.log("MongoDB connected")
  } catch (err) {
    console.error("Connection failed:", err)
    process.exit(1)
  }
}

Defining Schemas and Models

Schema Definition with Types and Options

Schema Definition with Types and Options
const { Schema, model } = require("mongoose")

const userSchema = new Schema({
  name: {
    type: String,
    required: [true, "Name is required"],
    minlength: 2,
    maxlength: 100,
    trim: true
  },
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true,
    match: [/^\S+@\S+\.\S+$/, "Invalid email format"]
  },
  age: {
    type: Number,
    min: [0, "Age cannot be negative"],
    max: [150, "Age seems too high"]
  },
  role: {
    type: String,
    enum: ["admin", "editor", "user"],
    default: "user"
  },
  active: {
    type: Boolean,
    default: true
  },
  hobbies: [String],
  address: {
    street: String,
    city: String,
    zip: String
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
}, {
  timestamps: true   // auto-adds createdAt and updatedAt
})

// Create the model (maps to "users" collection)
const User = model("User", userSchema)
module.exports = User

CRUD with Mongoose

Create, Read, Update, Delete with Mongoose

Create, Read, Update, Delete with Mongoose
// CREATE
const alice = new User({ name: "Alice", email: "alice@example.com", age: 29 })
await alice.save()

// Or use create() shorthand
const bob = await User.create({ name: "Bob", email: "bob@example.com", age: 34 })

// READ
const allUsers = await User.find()
const activeUsers = await User.find({ active: true }).sort({ name: 1 }).limit(10)
const alice = await User.findOne({ email: "alice@example.com" })
const userById = await User.findById("64a1f2c3e4b0a1b2c3d4e5f6")

// Projection - select specific fields
const names = await User.find({}, "name email -_id")

// UPDATE
await User.findByIdAndUpdate(
  "64a1f2c3e4b0a1b2c3d4e5f6",
  { $set: { age: 30 } },
  { new: true, runValidators: true }  // new: true returns updated doc
)

await User.updateMany({ role: "user" }, { $set: { active: false } })

// DELETE
await User.findByIdAndDelete("64a1f2c3e4b0a1b2c3d4e5f6")
await User.deleteMany({ active: false })

Virtuals, Middleware, and Populate

Virtuals, Pre/Post Hooks, and populate()

Virtuals, Pre/Post Hooks, and populate()
// VIRTUAL - computed property not stored in DB
userSchema.virtual("fullName").get(function() {
  return `${this.firstName} ${this.lastName}`
})

// PRE HOOK - runs before save
userSchema.pre("save", async function(next) {
  if (this.isModified("password")) {
    this.password = await bcrypt.hash(this.password, 12)
  }
  next()
})

// POST HOOK - runs after save
userSchema.post("save", function(doc) {
  console.log("User saved:", doc._id)
})

// POPULATE - resolve references to other collections
const orderSchema = new Schema({
  userId: { type: Schema.Types.ObjectId, ref: "User" },
  total: Number
})
const Order = model("Order", orderSchema)

// Populate userId with the full User document
const orders = await Order.find().populate("userId", "name email")
// orders[0].userId is now the full User object, not just an ObjectId

Mongoose Schema Types Reference

Mongoose Schema Types Reference
// Mongoose Schema Types:
// String, Number, Date, Buffer, Boolean, Mixed, ObjectId, Array, Decimal128, Map

// Common field options:
// type        - data type
// required    - true or [true, "error message"]
// default     - default value or function
// unique      - creates a unique index
// index       - creates an index
// sparse      - sparse index
// min/max     - for Number and Date
// minlength/maxlength - for String
// enum        - array of allowed values
// match       - regex pattern for String
// trim        - remove whitespace
// lowercase   - convert to lowercase
// uppercase   - convert to uppercase
// immutable   - cannot be changed after creation
// validate    - custom validator function

// Example with custom validator
score: {
  type: Number,
  validate: {
    validator: (v) => v >= 0 && v <= 100,
    message: "Score must be between 0 and 100"
  }
}

Applied guide for Mongoose

Use Mongoose when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real MongoDB task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.

A reliable practice flow is: create the smallest working collection query, add one normal case, add one edge case such as missing, repeated, empty, or boundary input, and then confirm the result with explain plan and sample documents. If the result surprises you, reduce the code until the behavior is visible again.

The most common trap here is copying the syntax before understanding the behavior. Avoid it by writing one sentence before the code that explains why Mongoose is the right choice. After the code runs, verify the lesson by doing this: change one input and explain the changed output.

  • Identify the exact problem solved by Mongoose.
  • Trace document shape and index before and after the main operation.
  • Keep one intentionally broken version and explain the fix.
  • Connect the example to a product catalog or user activity store so the idea feels concrete.
Key Takeaways
  • I can explain where Mongoose fits inside a product catalog or user activity store.
  • I can point to the exact document shape and index affected by this topic.
  • I tested a normal case and an edge case involving missing, repeated, empty, or boundary input.
  • I verified the result with explain plan and sample documents instead of assuming it worked.
  • I can describe the main mistake: copying the syntax before understanding the behavior.
Common Mistakes to Avoid
WRONG Copying the syntax before understanding the behavior.
RIGHT Write the expected behavior first, then make the example prove it.
A one-line expectation turns the code from copied syntax into a testable idea.
WRONG Practicing only the perfect input.
RIGHT Also test missing, repeated, empty, or boundary input before considering the lesson complete.
The edge case is where most interview follow-up questions begin.
WRONG Looking only at the final output.
RIGHT Trace document shape and index through each important step.
Tracing makes debugging faster because you can see the first incorrect state.

Practice Tasks

  • Build one small collection query that demonstrates Mongoose in a product catalog or user activity store.
  • Change the example to include missing, repeated, empty, or boundary input and record the difference.
  • Break the example by deliberately copying the syntax before understanding the behavior, then write the corrected version.
  • Explain the finished example in five bullet points: input, operation, output, failure case, and verification.

Frequently Asked Questions

Use it when the problem matches the behavior shown in the example and when the result can be verified through explain plan and sample documents.

Start with a tiny case, then test missing, repeated, empty, or boundary input. The main warning sign is copying the syntax before understanding the behavior.

Trace document shape and index, predict the result, run the example, and compare your prediction with the actual output.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.