MongoDB에 저장할 문서를 붙여넣으면 CommonJS 형식의 Mongoose 스키마 파일이 나옵니다. new Schema({...})로 필드를 정의하고 mongoose.model()로 모델을 등록한 뒤 module.exports로 내보내는 구조라, Express 프로젝트의 models/ 폴더에 그대로 저장해 require하면 됩니다.
필드 경로는 JSON 키를 그대로 씁니다. 그래서 컬렉션에 이미 쌓인 문서도 이름을 바꾸지 않고 이 스키마로 읽을 수 있습니다. 문서 여러 개를 배열로 넣으면 모든 문서의 키를 합쳐 하나의 스키마를 만듭니다.
mongoexport 결과를 배열로 감싸 넣어도 됩니다.모델 이름을 입력합니다(기본값 MyModel). 띄어쓰기를 넣어도 되며 blog comment는 BlogComment가 됩니다.models/Comment.js 같은 파일로 저장하고 라우터에서 const Comment = require('./models/Comment')로 불러옵니다.[
{ "author": "mina", "body": "Great post!", "likes": 3, "approved": true, "posted_at": "2024-05-01T09:30:00Z" },
{ "author": "leo", "body": "Typo in step 2", "likes": 0, "approved": false, "posted_at": "2024-05-02T11:00:00Z", "reply_to": "6634a1" }
]const mongoose = require('mongoose');
const { Schema } = mongoose;
const commentSchema = new Schema({
_id: { type: Schema.Types.ObjectId, auto: true },
author: { type: Schema.Types.String, required: true },
body: { type: Schema.Types.String, required: true },
likes: { type: Schema.Types.Number, required: true },
approved: { type: Schema.Types.Boolean, required: true },
posted_at: { type: Schema.Types.Date, required: true },
reply_to: { type: Schema.Types.String }
});
const Comment = mongoose.model('Comment', commentSchema);
module.exports = Comment;reply_to는 두 번째 댓글에만 있어서 required 없이 만들어졌고, ISO 날짜 문자열인 posted_at은 Schema.Types.Date가 됐습니다. 두 필드 모두 snake_case 이름을 그대로 유지하는데, 스키마 경로가 저장된 키와 같아야 하기 때문입니다.
Schema.Types.Number, true/false → Schema.Types.Boolean, 2024-05-01이나 2024-05-01T09:30:00Z 같은 ISO 8601 문자열 → Schema.Types.Date, 나머지 문자열 → Schema.Types.String."01234")는 String으로 남아서 우편번호나 전화번호의 앞자리 0이 사라지지 않습니다.Schema.Types.Mixed가 되고, 한 종류의 단순 값만 든 배열은 [Schema.Types.String]처럼 타입이 붙은 배열, 그 밖의 배열은 [Schema.Types.Mixed]가 됩니다.required: true는 모든 문서에 비어 있지 않은 값이 있을 때만 붙습니다. 배열은 Mongoose가 없으면 []로 채우므로 붙이지 않습니다._id 키는 빼고, 대신 _id: { type: Schema.Types.ObjectId, auto: true }를 선언합니다.home-url처럼 JavaScript 식별자가 될 수 없는 키는 따옴표로 감싼 키로 씁니다.프론트엔드와 요청 본문 형태를 먼저 정해 두었다면, 그 JSON으로 스키마 초안을 만들어 POST 라우트의 Comment.create(req.body)에 바로 연결할 수 있습니다.
strict: false나 네이티브 드라이버로 채워 온 컬렉션에서 문서 몇 개를 꺼내 넣어 보세요. 항상 있는 필드와 가끔만 있는 필드가 required 유무로 바로 드러납니다.
mongoose.model('Comment', ...)로 등록되고, Mongoose는 이 이름을 소문자 복수형으로 바꿔 컬렉션 이름으로 씁니다(comments). 기존 컬렉션 이름이 다르면 세 번째 인자로 직접 지정하세요.Mixed 필드는 내부 값을 바꿔도 변경으로 감지되지 않습니다. 중첩 값을 수정한 뒤에는 save() 전에 doc.markModified('profile')을 호출하거나, 그 필드를 하위 스키마로 바꾸세요.unique 제약은 만들지 않습니다. 조회 기준이 되는 필드에는 unique: true나 index: true를 직접 추가하세요.import / export default)으로 받을 수 있나요?이 페이지는 require와 module.exports를 쓰는 CommonJS만 만듭니다. "type": "module" 프로젝트라면 첫 두 줄을 import mongoose, { Schema } from 'mongoose'로, 마지막 줄을 export default Comment로 바꾸면 됩니다. TypeScript나 NestJS라면 JSON → Mongoose (TS) 페이지를 쓰세요.
createdAt, updatedAt을 자동으로 넣으려면요?생성 코드에는 스키마 옵션이 없습니다. new Schema({...}, { timestamps: true })처럼 두 번째 인자를 추가하면 Mongoose가 두 필드를 관리하니, JSON에서 온 같은 이름의 필드는 지워 주세요.
required 필드에 빈 문자열을 저장하면 어떻게 되나요?Mongoose의 문자열 required 검사는 ""를 값이 없는 것으로 봅니다. 그래서 예시에서 빈 문자열이던 필드는 처음부터 required 없이 만들어집니다.