next/models/stories/review.ts

76 lines
1.6 KiB
TypeScript

import mongoose, { Schema, PopulatedDoc, Document, Model } from "mongoose";
import SequenceFactory from "mongoose-sequence";
import { hasMigrated } from "~/lib/dbconfig";
import { populate, populateSelected } from "~/lib/functions";
import { IUser } from "~/models/user";
const AutoIncrement = SequenceFactory(mongoose);
export interface IReview {
_id: number;
text: string;
leftOn: number;
whichChapter: number;
author: PopulatedDoc<IUser & Document>;
datePosted: Date;
replyingTo: PopulatedDoc<IReview & Document> | null;
replies: PopulatedDoc<IReview & Document>[];
}
const CommentSchema = new mongoose.Schema<IReview>({
_id: {
type: Number,
},
text: {
type: String,
},
leftOn: {
type: Number,
},
whichChapter: {
type: Number,
},
author: {
type: Number,
ref: "User",
},
datePosted: {
type: Date,
default: new Date(),
},
replyingTo: {
default: null,
type: Number,
ref: "Review",
},
replies: [
{
default: null,
type: Number,
ref: "Review",
},
],
});
CommentSchema.virtual("story", {
ref: "Story",
localField: "leftOn",
foreignField: "_id",
justOne: true,
});
CommentSchema.pre("findOne", populate("replies"))
.pre("find", populate("replies"))
.pre("findOne", populate("commentAuthor"))
.pre("find", populate("commentAuthor"))
.pre("findOne", populateSelected("replyingTo", "-replies"))
.pre("find", populateSelected("replyingTo", "-replies"));
hasMigrated && CommentSchema.plugin(AutoIncrement, { id: "reviews" });
export const Review: Model<IReview> =
/* mongoose.models.Review || */ mongoose.model(
"Review",
CommentSchema,
"reviews",
);