I am using Express and MongoDB with Mongoose. I have a Site model, which contains Units, and the Units contain Entries
┌────────────────┐
│ │
│ Site │
│ │
├────────────────┘
│
│ ┌────────────────┐
│ │ │
└──► Units │
│ │
├────────────────┘
│
│ ┌────────────────┐
│ │ │
└───► Entries │
│ │
└────────────────┘
When I run a delete request for a Site, I would like for the Entries to be deleted, then the Units, and then the Site.
Currently, I'm able to successfully get pre deleteOne to remove the Unit and then the Site when deleting the site in my Site model:
//Site Model
const mongoose = require("mongoose");
const SiteSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
unique: [true, "Duplicate name value entered"],
},
description: {
type: String,
required: true,
}
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
// Reverse populate with virtuals
SiteSchema.virtual("units", {
ref: "Unit",
localField: "_id",
foreignField: "site",
justOne: false,
});
SiteSchema.pre("deleteOne", { document: true, query: false }, function (next) {
// Remove units associated with site
this.model("Unit").deleteMany({ site: this._id }, next);
next();
});
module.exports = mongoose.model("Site", SiteSchema);
But once I introduce the pre deleteMany in the Unit model to remove the Entries, it no longer deletes the Units, and it doesn't remove the Entries. It looks like the pre deleteMany in the Unit model is running just from a console log of "Ran", but something in there is preventing it from completing.
//Unit Model
const mongoose = require("mongoose");
const UnitSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
unique: true,
},
site: {
type: mongoose.Schema.ObjectId,
ref: "Site",
required: true,
},
description: {
type: String,
required: true,
},
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
// Reverse populate with virtuals
UnitSchema.virtual("entries", {
ref: "Entry",
localField: "_id",
foreignField: "unit",
justOne: false,
});
// When a site is deleted, it deletes units, which should delete entries
UnitSchema.pre("deleteMany", function (next) {
console.log("Ran");
this.model("Entry").deleteMany({ unit: this._id }, next);
next();
});
module.exports = mongoose.model("Unit", UnitSchema);
Here is my entry model in case you need it:
const mongoose = require("mongoose");
const EntrySchema = new mongoose.Schema(
{
title: {
type: String,
required: [true, "Please add a title"],
unique: true,
trim: true,
maxlength: [70, "Title can not be more than 70 characters"],
},
description: {
type: String,
required: [true, "Please add a short description"],
maxlength: [500, "Description can not be more than 500 characters"],
},
unit: {
type: mongoose.Schema.ObjectId,
ref: "Unit",
required: true,
}
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
module.exports = mongoose.model("Entry", EntrySchema);