I have a parent document, ParentDoc
, with an embedded sub document in mongoose.
If I delete an embedded sub document, how do I ensure all of its reference documents, RefObject
, get deleted?
With embedded documents, .remove()
middleware will only run when you call .remove()
on the parent document. So I can't trigger a pre remove hook on the subDocSchema
and delete the referenced object in there.
Is there anyway to delete a subdocument's reference objects when the subdocument is deleted? If not, is this a case where I should have instead made the sub document a referenced document?
const parentDocSchema = new mongoose.Schema({
name: String,
subDocuments: [subDocSchema],
});
const ParentDoc = mongoose.model("ParentDoc", parentDocSchema);
const subDocSchema = new mongoose.Schema({
name: String,
refObjects: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "refObject",
},
],
});
const RefObject = mongoose.model(
"RefObject",
new mongoose.Schema({
name: String,
})
);