node.js - 如何在 pre deleteOne 中获取 mongoose deleteMany 以触发另一个模型上的 pre deleteMany?
问题描述
我在 Mongoose 中使用 Express 和 MongoDB。我有一个站点模型,其中包含单元,并且单元包含条目
┌────────────────┐
│ │
│ Site │
│ │
├────────────────┘
│
│ ┌────────────────┐
│ │ │
└──► Units │
│ │
├────────────────┘
│
│ ┌────────────────┐
│ │ │
└───► Entries │
│ │
└────────────────┘
当我对站点运行删除请求时,我希望删除条目,然后是单元,然后是站点。
目前,在我的站点模型中删除站点时,我能够成功地获得 pre deleteOne 以删除单元,然后是站点:
//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);
但是一旦我在 Unit 模型中引入 pre deleteMany 来删除条目,它就不再删除单元,也不会删除条目。看起来 Unit 模型中的 pre deleteMany 只是从“Ran”的控制台日志运行,但其中的某些东西阻止它完成。
//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);
如果您需要,这是我的入门模型:
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);
解决方案
推荐阅读
- console - 停用 setinterval 功能?
- sql - 如何优化查询以计算与行相关的日期时间关系?
- node.js - 抽头测试超时
- c# - Winform 图表 - 固定 X 轴
- reactjs - 如何使用axios调用GET api在BODY中发送数据?
- python - 迭代for循环时如何将多个系列(熊猫)添加在一起?
- javascript - 如何使用 Vuejs 进行 Onload 事件——特别是如何将脚本放入方法中以及在 html 中获取调用的方式
- javascript - 从多个选择下拉列表中获取选定的选项值
- angular - getComputedStyle() 是获取 Angular 中 css 设置样式的唯一方法吗?
- javascript - 在 JSON 的每个元素处推送不同的值