【发布时间】:2021-11-24 04:58:53
【问题描述】:
我有 3 个模型,Book & Author & 'Category'。
作者可以有多本书。
类别可以有多本书,如果没有有效的作者或类别,则无法创建图书
const schema = new mongoose.Schema(
{
title: dbHelpers.bookTitleValidation,
image: dbHelpers.imageValidation,
author: dbHelpers.bookAuthorValidation,
category: dbHelpers.categoryValidation,
reviews: [dbHelpers.bookReviewValidation],
rates: [dbHelpers.bookRateValidation],
},
{ timestamps: true }
);
我想做的是:
- 尝试保存新书时,我应该验证关联的作者和类别是否有效,因此我创建了一个预“保存”中间件来验证这一点[在导出模型之前在 Book 模型中]。
- 删除作者或类别时,应删除所有相关书籍,因此我再次创建了一个预“删除”中间件来实现此目的[在导出模型之前的作者和类别模型中]。
这是Book 模型中的预“保存”中间件
schema.pre("save", async function (next) {
const author = await authorModel.findById(this.author);
if (!author) {
next(new Error("Author is not valid!"));
}
const category = await categoryModel.findById(this.category);
if (!category) {
next(new Error("Category is not valid!"));
}
next();
});
这是Author 模型中的预“删除”中间件
schema.pre("remove", { document: true }, async function (next) {
await booksModel.find({ author: this.id }).remove();
let imgFileName = this.image.split("/")[3];
console.log("imgFileName: ", imgFileName);
await rm(__dirname + "/../" + "public/authors/" + imgFileName + ".png");
next();
});
问题是要让这些中间件工作,我必须执行以下操作 [这是我所知道的]:
- const booksModel = require("./Book"); //在作者模型中
- const authorModel = require("./Author"); // 在书籍模型中
这给了我一个authorModel 的空对象,在搜索它之后我发现这是由于循环依赖。
如何解决这个问题并继续使用这些中间件?
【问题讨论】: