ODM Mongoose สำหรับสร้างแบบจำลองข้อมูล
เรียนรู้การกำหนดสคีมาและแบบจำลองด้วย Mongoose เพื่อจัดโครงสร้างข้อมูลใน MongoDB อย่างมีประสิทธิภาพ
ODM Mongoose สำหรับสร้างแบบจำลองข้อมูล เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Node.js Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Meet Mongoose Schemas
In the last lesson, we connected to MongoDB. Now, let's learn how to structure our data with Mongoose and Schemas.
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward, schema-based solution to model your application data, making it easier to work with MongoDB.
Why Schemas Matter
MongoDB is a NoSQL database, meaning it's schema-less by default. While this offers great flexibility, it can lead to inconsistent data if not managed.
Mongoose schemas bring structure and consistency:
- Define Data Shape: What fields a document should have.
- Data Types: Ensure fields store correct types (String, Number, etc.).
- Validation: Add rules like 'required' or 'minimum length'.
Defining Your First Schema
Let's define a basic schema for a Book. We'll specify properties like title and author, and their expected data types.
First, we need to import Mongoose, then create a new Schema object.
const mongoose = require('mongoose');
// Define the Book Schema
const bookSchema = new mongoose.Schema({
title: String,
author: String,
pages: Number,
isPublished: Boolean
});
console.log('Book Schema defined!');
// In a real app, this schema would be used to create a model.Common Schema Types
Mongoose supports many data types that map to JavaScript types and MongoDB BSON types. Here are some of the most common ones:
- String: For text like names, descriptions.
- Number: For numerical values like age, price.
- Boolean: For true/false values.
- Date: For storing dates and times.
- ObjectId: A special type for unique IDs, often used for references between documents.
Schema Options: Required & Default
Beyond just types, schemas allow you to add options to each field. These options control behavior and validation. Two common ones are required and default.
required: true: Means this field must have a value.default: 'value': Provides a fallback value if none is specified during document creation.
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true // Name is mandatory
},
price: {
type: Number,
required: true,
default: 0 // Default price is 0 if not set
},
createdAt: {
type: Date,
default: Date.now // Automatically set current date
}
});
console.log('Product Schema with options defined!');Creating a Mongoose Model
A schema is like a blueprint. To actually interact with your MongoDB collection, you need to create a Model from that schema.
A Mongoose Model is a wrapper around the schema that provides an interface for the database: creating, querying, updating, and deleting records in a specific collection.
const mongoose = require('mongoose');
// Define a simple User Schema
const userSchema = new mongoose.Schema({
name: String,
email: String
});
// Create a Model from the schema
// 'User' is the singular name. Mongoose will use 'users' as collection name.
const User = mongoose.model('User', userSchema);
console.log('User Model created from schema!');
// Now you can use the User model to interact with the 'users' collection.Basic Field Validation
Mongoose schemas offer built-in validation to ensure data integrity before saving to the database. This helps keep your data clean and consistent.
You can define validators like minlength, maxlength, and enum (a list of allowed values) directly within your schema definition.
const mongoose = require('mongoose');
const taskSchema = new mongoose.Schema({
description: {
type: String,
required: true,
minlength: 5, // Must be at least 5 characters
maxlength: 100 // Max 100 characters
},
status: {
type: String,
enum: ['pending', 'completed', 'cancelled'], // Only these values allowed
default: 'pending'
}
});
console.log('Task Schema with validation rules defined!');Embedding Documents
Sometimes, one document logically 'contains' another. Mongoose allows you to embed schemas directly within other schemas, creating nested documents.
This is useful for tightly coupled data that doesn't need its own separate collection, like an address within a user profile.
const mongoose = require('mongoose');
// Define an Address Schema
const addressSchema = new mongoose.Schema({
street: String,
city: String,
zip: String
});
// Embed Address Schema within a Person Schema
const personSchema = new mongoose.Schema({
name: String,
// The 'address' field will be a nested document using addressSchema
address: addressSchema
});
console.log('Person Schema with embedded Address Schema defined!');
// A 'Person' document will now contain an 'address' object.Quick Check: Schema Fields
Imagine you're building a schema for a blog post. It needs a title (required string), content (string), and publishDate (date, defaults to now).
Which of the following Mongoose schema definitions correctly sets up these fields and their options?
Recap: Schemas & Models
Great job! You've learned the essentials of Mongoose schemas and models:
- Schemas define the structure, data types, and validation rules for your MongoDB documents.
- They provide consistency in a schema-less database.
- You create Models from schemas to interact with specific collections in MongoDB.
- We explored common types, options like
requiredanddefault, and even embedding documents.
Next, we'll use these models to perform CRUD operations (Create, Read, Update, Delete)!
คำถามที่พบบ่อย
บทเรียน “ODM Mongoose สำหรับสร้างแบบจำลองข้อมูล” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ODM Mongoose สำหรับสร้างแบบจำลองข้อมูล” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ODM Mongoose สำหรับสร้างแบบจำลองข้อมูล”
เรียนรู้การกำหนดสคีมาและแบบจำลองด้วย Mongoose เพื่อจัดโครงสร้างข้อมูลใน MongoDB อย่างมีประสิทธิภาพ คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “ODM Mongoose สำหรับสร้างแบบจำลองข้อมูล” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- เชื่อมต่อ Node.js กับ MongoDB
- ODM Mongoose สำหรับสร้างแบบจำลองข้อมูล
- การดำเนินการ CRUD ด้วย Mongoose
- การสืบค้นและกรองข้อมูลด้วย Mongoose