无法解决猫鼬模型的循环依赖

Ate*_*res 3 mongoose node.js express

我有 3 个模型,Book&& Author“类别”。作者可以拥有多本书。类别可以包含多本书,如果没有有效的作者或类别,则无法创建书籍

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 }
);
Run Code Online (Sandbox Code Playgroud)

我想做的是:

  • 当尝试保存一本新书时,我应该验证关联的作者和类别是否有效,因此我创建了一个预“保存”中间件来验证这一点[在导出模型之前在图书模型中]。
  • 删除作者或类别时,应删除所有关联的书籍,因此我再次创建了一个预“删除”中间件来实现此目的[在导出模型之前在作者和类别模型中]。

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();
});
Run Code Online (Sandbox Code Playgroud)

这是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();
});
Run Code Online (Sandbox Code Playgroud)

问题是要使这些中间件工作,我必须执行以下操作[这是我知道的方式]:

  • const booksModel = require("./Book"); //在作者模型中
  • constauthorModel = require("./Author"); // 在书籍模型中

这给了我一个空对象authorModel,在搜索它之后我发现这是由于循环依赖造成的。

我该如何解决这个问题并仍然使用这些中间件?

Ate*_*res 10

我通过不需要模型相互连接来解决这个问题。

为了访问猫鼬模型,我使用了以下方法:

mongoose.model('MODEL_NAME').something
Run Code Online (Sandbox Code Playgroud)

通过这种方式,我能够消除循环依赖并仍然访问模型。


参考:

硬解决方案:使用依赖注入器。简单的解决方案:如果您使用 mongoose.model('Message', MessageSchema); 创建模型 然后你可以使用 mongoose.model('Message'); 访问模型,所以你需要做的就是 require('mongoose'); 在文件中访问您的模型。

https://github.com/Automattic/mongoose/issues/3826#issuecomment-178047542