ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Schema, model]
    Database/MongoDB 2022. 1. 20. 19:08
    1. Shema
      • 정의
        • mongoose의 모든 것은 Schema로부터 시작한다. 
        • 각 Schema는 MongoDB 컬렉션에 매핑되고 해당 컬렉션 내 문서의 모양 정의
        • 하나하나 정보 지정한다.
          • type, maxlength..
      • ShemaTypes
        • String
        • Number
        • Date
        • Buffer
        • Boolean
        • Mixed
        • ObjectId
        • Array
        • Decimal128
        • Map
      • 예시
        // schema 예시
        
        const productSchema = mongoose.Shema({
            writer: {
                type: schema.Types.ObjectId,
                ref: 'User'
            },
            title: {
                type: String,
                maxlength: 50
            },
            description: {
                type: String
            },
        }, { timestamps: true })
        
        // timestaps
        // createAt, updateAt 필드 자동 생성
    2. Model
      • schema정의를 사용하기 위해 Model로 변환해야 한다.
      • mongoose.model(modelName, schema)
      • 예시
        // model
        
        const Product = mongoose.model("Product", productSchema);​
    3. Shema생성 및 Model 생성
      • // schema 생성
        
        // Blog.js
        import mongoose from 'mongoose';
        // const mongoose = require("mongoose");  동일
        
        const blogSchema = mongoose.Schema({
            title: String,  // String is shorthand for {type: String}
            author: String,
            body: String,
            comments: 
                [{
                    body: String,
                    date: Date
                }],
            date: {
                type: Date,
                default: Date.now
            },
            hidden: Boolean,
            meta: {
                votes: Number,
                favs: Number
            }
        });
        
        // model 생성
        // 첫 번째 인자 : collection 이름
        // 두 번째 인자 : 위 생성한 스키마
        
        const Blog = mongoose.model('Blog', blogSchema);
        
        // 내보내기 (다른 곳에서도 사용할 수 있도록)
        module.exports = { Blog };

    'Database > MongoDB' 카테고리의 다른 글

    [save, insertOne] - 데이터 저장  (0) 2022.01.21
    [mongoose 설치]  (0) 2022.01.20
Designed by Tistory.