next/models/stories/review.ts

85 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-10-03 01:22:43 -04:00
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;
2023-10-03 01:22:43 -04:00
replies: PopulatedDoc<IReview & Document>[];
}
const CommentSchema = new mongoose.Schema<IReview>({
_id: {
2023-10-03 01:22:43 -04:00
type: Number,
},
text: {
2023-10-03 01:22:43 -04:00
type: String,
},
leftOn: {
2023-10-03 01:22:43 -04:00
type: Number,
},
whichChapter: {
2023-10-03 01:22:43 -04:00
type: Number,
},
author: {
type: Number,
2023-10-03 01:22:43 -04:00
ref: "User",
},
datePosted: {
type: Date,
2023-10-03 01:22:43 -04:00
default: new Date(),
},
replyingTo: {
default: null,
type: Number,
2023-10-03 01:22:43 -04:00
ref: "Review",
},
2023-10-03 01:22:43 -04:00
replies: [
{
default: null,
type: Number,
ref: "Review",
},
],
});
2023-10-03 01:22:43 -04:00
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 &&
!mongoose.models.Review &&
CommentSchema.plugin(AutoIncrement, { id: "reviews" });
2023-10-03 01:22:43 -04:00
export const Review: Model<IReview> =
/* mongoose.models.Review || */ mongoose.model(
modelName,
2023-10-03 01:22:43 -04:00
CommentSchema,
"reviews",
);