const mongoose = require("mongoose"); const PostSchema = new mongoose.Schema( { user: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true, index: true, }, content: { type: String, required: true, }, imageUrl: { type: String, }, cloudinaryPublicId: { type: String, }, likes: [ { type: mongoose.Schema.Types.ObjectId, ref: "User", }, ], commentsCount: { type: Number, default: 0, }, }, { timestamps: true, }, ); // Index for querying posts by creation date PostSchema.index({ createdAt: -1 }); // Update user relationship when post is created PostSchema.post("save", async function (doc) { const User = mongoose.model("User"); // Add post to user's posts if not already there await User.updateOne( { _id: doc.user }, { $addToSet: { posts: doc._id } } ); }); // Cascade cleanup when a post is deleted PostSchema.pre("deleteOne", { document: true, query: false }, async function () { const User = mongoose.model("User"); // Remove post from user's posts await User.updateOne( { _id: this.user }, { $pull: { posts: this._id } } ); }); module.exports = mongoose.model("Post", PostSchema);