const mongoose = require("mongoose"); const StreetSchema = new mongoose.Schema( { name: { type: String, required: true, }, location: { type: { type: String, enum: ["Point"], required: true, }, coordinates: { type: [Number], required: true, }, }, adoptedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, status: { type: String, enum: ["available", "adopted"], default: "available", }, }, { timestamps: true, }, ); StreetSchema.index({ location: "2dsphere" }); StreetSchema.index({ adoptedBy: 1 }); StreetSchema.index({ status: 1 }); // Cascade cleanup when a street is deleted StreetSchema.pre("deleteOne", { document: true, query: false }, async function () { const User = mongoose.model("User"); const Task = mongoose.model("Task"); // Remove street from user's adoptedStreets if (this.adoptedBy) { await User.updateOne( { _id: this.adoptedBy }, { $pull: { adoptedStreets: this._id } } ); } // Delete all tasks associated with this street await Task.deleteMany({ street: this._id }); }); // Update user relationship when street is adopted StreetSchema.post("save", async function (doc) { if (doc.adoptedBy && doc.status === "adopted") { const User = mongoose.model("User"); // Add street to user's adoptedStreets if not already there await User.updateOne( { _id: doc.adoptedBy }, { $addToSet: { adoptedStreets: doc._id } } ); } }); module.exports = mongoose.model("Street", StreetSchema);