next/models/stories/review.ts
☙◦ The Tablet ❀ GamerGirlandCo ◦❧ a8e113e969
refactor(db/models): remove model existence guards
this way, plugins are registered if `hasMigrated` is true. we've already enabled automatically overwriting models, therefore, the guard's condition will always be false
2023-12-29 16:36:26 -05:00

83 lines
1.8 KiB
TypeScript

import mongoose, { Schema, PopulatedDoc, Document, Model } from "mongoose";
import SequenceFactory from "mongoose-sequence";
import { hasMigrated } from "@dbconfig";
import { populate, populateSelected } from "@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,
});
const modelName = "Review";
CommentSchema
// .pre("findOne", populateSelected("replyingTo", modelName, "-replies -author"))
// .pre("find", populateSelected("replyingTo", modelName, "-replies -author"))
.pre("findOne", populate("replies", modelName))
.pre("find", populate("replies", modelName))
.pre(
"findOne",
populateSelected("author", "User", "profile username _id blocked"),
)
.pre(
"find",
populateSelected("author", "User", "profile username _id blocked"),
);
hasMigrated && CommentSchema.plugin(AutoIncrement, { id: "reviews" });
export const Review: Model<IReview> =
/* mongoose.models.Review || */ mongoose.model(
modelName,
CommentSchema,
"reviews",
);