All files / models Post.ts

0% Statements 0/10
0% Branches 0/2
100% Functions 0/0
0% Lines 0/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89                                                                                                                                                                                 
import mongoose, { Schema, Document, Model, Types } from "mongoose";
 
export interface IPost extends Document {
  authorId: Types.ObjectId;
  categoryId: Types.ObjectId;
  title: string;
  summary: string;
  body: string;
  tags?: string[];
  visibility: "public" | "members" | "private";
  allowComments: boolean;
  deletedAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}
 
const PostSchema = new Schema<IPost>(
  {
    authorId: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: [true, "Author is required"],
      index: true,
    },
    categoryId: {
      type: Schema.Types.ObjectId,
      ref: "Category",
      required: [true, "Category is required"],
      index: true,
    },
    title: {
      type: String,
      required: [true, "Title is required"],
      trim: true,
      maxlength: [100, "Title cannot exceed 100 characters"],
    },
    summary: {
      type: String,
      required: [true, "Summary is required"],
      trim: true,
      maxlength: [280, "Summary cannot exceed 280 characters"],
    },
    body: {
      type: String,
      required: [true, "Body is required"],
    },
    tags: {
      type: [String],
      default: [],
    },
    visibility: {
      type: String,
      enum: ["public", "members", "private"],
      default: "public",
    },
    allowComments: {
      type: Boolean,
      default: true,
    },
    deletedAt: {
      type: Date,
    },
  },
  {
    timestamps: true,
  }
);
 
// Compound indexes for performance optimization
// Index for filtering out soft-deleted posts
PostSchema.index({ deletedAt: 1, createdAt: -1 });
 
// Index for category filtering with soft-delete check
PostSchema.index({ categoryId: 1, deletedAt: 1, createdAt: -1 });
 
// Index for author filtering with soft-delete check
PostSchema.index({ authorId: 1, deletedAt: 1, createdAt: -1 });
 
// Index for visibility filtering
PostSchema.index({ visibility: 1, deletedAt: 1, createdAt: -1 });
 
// Index for tag searches
PostSchema.index({ tags: 1 });
 
const Post: Model<IPost> =
  mongoose.models.Post || mongoose.model<IPost>("Post", PostSchema);
 
export default Post;