0Pricing
Node.js Backend Development Bootcamp · 강의

데이터 모델링을 위한 Mongoose ODM

Mongoose로 스키마와 모델을 정의하고 MongoDB에서 데이터를 효과적으로 구조화하는 방법을 배웁니다.

데이터 모델링을 위한 Mongoose ODM은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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 required and default, and even embedding documents.

Next, we'll use these models to perform CRUD operations (Create, Read, Update, Delete)!

자주 묻는 질문

“데이터 모델링을 위한 Mongoose ODM” 강의는 무료인가요?

네 — “데이터 모델링을 위한 Mongoose ODM” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“데이터 모델링을 위한 Mongoose ODM”에서 뭘 배우나요?

Mongoose로 스키마와 모델을 정의하고 MongoDB에서 데이터를 효과적으로 구조화하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“데이터 모델링을 위한 Mongoose ODM” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Node.js를 MongoDB에 연결하기
  2. 데이터 모델링을 위한 Mongoose ODM
  3. Mongoose로 CRUD 작업하기
  4. Mongoose로 데이터 조회 및 필터링
← Node.js Backend Development Bootcamp(으)로 돌아가기