import mongoose, { Document, Schema } from 'mongoose';
import mongoosePaginate from 'mongoose-paginate-v2';
export interface IPost extends Document {
title: string;
content: string;
author: string;
tags: string[];
likes: number;
comments: mongoose.Types.ObjectId[]; // 수정된 부분
}
const postSchema: Schema = new Schema({
title: { // 게시물 제목
type: String,
required: true,
trim: true
},
content: { // 게시물 내용
type: String,
required: true
},
author: { // 작성자 정보 (사용자 ID)
type: String,
required: true
},
likes: { // 좋아요 수
type: Number,
default: 0
},
comments: [{ // 댓글 목록
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}]
}, {
timestamps: true, // createdAt, updatedAt 필드 추가
versionKey: false // __v 필드에서 삭제
});
postSchema.plugin(mongoosePaginate);
const Post = mongoose.models.Post || mongoose.model<IPost, mongoose.PaginateModel<IPost>>('Post', postSchema, 'post');
export default Post;
import mongoosePaginate from 'mongoose-paginate-v2'
export interface IComment extends Document {
postId: mongoose.Types.ObjectId
author: string;
content: string;
likes: number;
}
const commentSchema: Schema = new Schema({
postId: { // 부모 post id
type: mongoose.Schema.Types.ObjectId,
ref: 'Post',
required: true
},
content: { // 게시물 내용
type: String,
required: true
},
author: { // 작성자 정보 (사용자 ID)
type: String,
required: true
},
likes: { // 좋아요 수
type: Number,
default: 0
}
}, {
timestamps: true, // createdAt, updatedAt 필드 추가
versionKey: false // __v 필드에서 삭제
})
commentSchema.plugin(mongoosePaginate)
const Comment = mongoose.models.Comment || mongoose.model<IComment, mongoose.PaginateModel<IComment>>('Comment', commentSchema, 'comment')
export default Comment
await dbConnect()
const { postId } = params
const result = await Post.findOne({ _id: postId }).populate('comments')
if (!result) {
return NextResponse.json({}, { status: 400 })
}
return NextResponse.json({ data: result })
}
findOne까지는 문제없는데 populate('comments') 에서 에러남 구글링해도 문제가 뭔질 모르겠네 gpt는 딴얘기만하고 살려주삼
Schema hasn't been r.egistered for model "Comment"
const result = await Post.findOne({ _id: postId }).toString().populate('comments')
?