MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Mongoose Connection Lifecycle, Schemas & Compiled Models0%
Study Materials
MongoDB & MongooseProgress 0%
1.1Document Databases vs Relational SQL: CAP Theorem & When to Use NoSQL1.2JSON vs BSON Data Types & MongoDB Internal Storage Engine (WiredTiger)1.3MongoDB Atlas Cloud Setup, Network Whitelisting & Compass GUI
3.1Mongoose Connection Lifecycle, Schemas & Compiled Models3.2Built-in & Custom Schema Validations with Custom Error Messages3.3Pre and Post Middleware Hooks (Document & Query Middleware)3.4Virtual Properties, Instance Methods & Static Model Methods
HomeTutorialsMongoDB & MongooseMongoose Connection Lifecycle, Schemas & Compiled Models
Built-in & Custom Schema Validations with Custom Error Messages

Mongoose Connection Lifecycle, Schemas & Compiled Models

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While the native MongoDB driver provides low-level querying flexibility, real-world enterprise applications require structured data models, type casting, validation rules, and business logic. Mongoose is the industry-standard Object Data Modeling (ODM) library for MongoDB and Node.js.


1. Connecting Mongoose to MongoDB

Mongoose provides an intelligent connection pool that buffers queries until the database connection is officially established:

1import mongoose from 'mongoose';
2 
3const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/msk_academy';
4 
5export async function connectDatabase() {
6 try {
7 const conn = await mongoose.connect(MONGODB_URI, {
8 maxPoolSize: 20, // Keep up to 20 socket connections open
9 serverSelectionTimeoutMS: 5000, // Timeout after 5s if server unreachable
10 socketTimeoutMS: 45000 // Close idle sockets after 45s
11 });
12 
13 console.log(`MongoDB Connected: ${conn.connection.host}`);
14 } catch (error) {
15 console.error(`Database connection error: ${error.message}`);
16 process.exit(1);
17 }
18}
19 
20// Connection lifecycle event listeners
21mongoose.connection.on('disconnected', () => console.warn('MongoDB connection lost!'));
22mongoose.connection.on('reconnected', () => console.log('MongoDB reconnected cleanly.'));

2. Defining Schemas and Compiling Models

  1. 1
    Schema: A blueprint that defines the structure of documents, default values, and data types within a collection.
  2. 2
    Model: A compiled constructor compiled from the Schema that provides the interface for querying and saving documents in MongoDB.
1import mongoose from 'mongoose';
2 
3const { Schema, model } = mongoose;
4 
5// 1. Define the Schema
6const courseSchema = new Schema(
7 {
8 title: {
9 type: String,
10 required: [true, 'Course title is mandatory'],
11 trim: true,
12 maxlength: [100, 'Title cannot exceed 100 characters']
13 },
14 slug: {
15 type: String,
16 required: true,
17 unique: true,
18 lowercase: true
19 },
20 price: {
21 type: Number,
22 required: true,
23 min: [0, 'Price cannot be negative']
24 },
25 level: {
26 type: String,
27 enum: {
28 values: ['Beginner', 'Intermediate', 'Advanced', 'All Levels'],
29 message: '{VALUE} is not a supported difficulty level'
30 },
31 default: 'All Levels'
32 },
33 isPublished: {
34 type: Boolean,
35 default: false
36 }
37 },
38 {
39 timestamps: true // Automatically injects and manages createdAt and updatedAt fields!
40 }
41);
42 
43// 2. Compile the Model (Creates 'courses' collection in lowercase plural)
44const Course = model('Course', courseSchema);
45 
46export default Course;

3. Creating and Querying with Mongoose Models

1// Create and save a new document
2const newCourse = await Course.create({
3 title: 'Next.js 15 Full-Stack Framework',
4 slug: 'nextjs-15-full-stack',
5 price: 3499,
6 level: 'Intermediate'
7});
8 
9// Find documents
10const publishedCourses = await Course.find({ isPublished: true })
11 .select('title price level') // Field projection
12 .sort('-price'); // Descending sort

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What is Mongoose in relation to MongoDB?
Question 2
When you compile a model with mongoose.model('Product', productSchema), what name will Mongoose give to the underlying collection in MongoDB by default?
Question 3
What does setting { timestamps: true } in the Mongoose Schema options do?
Question 4
What happens when Mongoose receives a database operation before the initial connection to the MongoDB server finishes?
Question 5
Which schema option removes surrounding whitespace from string inputs automatically before saving?

Next Lesson

Built-in & Custom Schema Validations with Custom Error Messages

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Delete Operations, Cursors, Limit, Skip & Sorting in MongoDBBuilt-in & Custom Schema Validations with Custom Error Messages

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master MongoDB & Mongoose with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext