猫鼬模型是另一个模型的后挂钩内的空对象

猫鼬模型是另一个模型的后挂钩内的空对象

本文介绍了猫鼬模型是另一个模型的后挂钩内的空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目有2个相互参照的模型.当删除一个模型的实例时,remove()方法将钩住另一个模型以删除依赖关系.

photo.model.js

const Album = require('./album');
       .
       .
// post hook of photo.remove()
schema.post('remove', (photo, next) => {

  console.log(Album);  // return empty obj {}

  Album.findById(photo._album, (error, album) => {
        // find album and remove photo
    });
});

删除里面的相册模型钩子返回空对象.我通过在钩子内部移动require语句找到了解决方法.

schema.post('remove', (photo, next) => {
  const Album = require('./album');
  Album.findById(photo._album, (error, album) => {
        // find album and remove photo
    });
});

但是该修复程序对我来说很难看,我的猜测是每次调用photo.remove()时都会调用require语句.


问题:

  • 我上面关于每次调用photo.remove()都会被调用require"的猜测是否正确?
  • 为什么不能将require放置在钩子外部并且与内部行为相同?
  • 无论如何,我可以将require放置在钩子外部并获得与放置在钩子中相同的行为吗?

解决方案

听起来像您有周期性依赖关系,其中photo.model.js需要album.js,而photo.model.js需要... c

要解决此问题,可以使用以下方法:

const mongoose = require('mongoose');

schema.post('remove', (photo, next) => {
  mongoose.model('Album').findById(photo._album, (error, album) => {
    // find album and remove photo
  });
});

My project has 2 models referring to one another. When the instances of one model are removed, remove() method will hook another model to remove the dependencies.

photo.model.js

const Album = require('./album');
       .
       .
// post hook of photo.remove()
schema.post('remove', (photo, next) => {

  console.log(Album);  // return empty obj {}

  Album.findById(photo._album, (error, album) => {
        // find album and remove photo
    });
});

Album model inside remove hook return empty object. I found the fix by moving require statement inside the hook.

schema.post('remove', (photo, next) => {
  const Album = require('./album');
  Album.findById(photo._album, (error, album) => {
        // find album and remove photo
    });
});

But the fix looks ugly to me and my guess is every time photo.remove() is called require statement is called.


Question:

  • Is my guess above about "require getting called every time photo.remove() is called" correct?
  • Why can't I place the require outside the hook and having same behavior as inside?
  • Is there anyway I can place require outside the hook and get the same behavior as placing it inside?

解决方案

It sounds like you have a cyclic dependency, where photo.model.js requires album.js which requires photo.model.js, ...

To work around that, you can use this:

const mongoose = require('mongoose');

schema.post('remove', (photo, next) => {
  mongoose.model('Album').findById(photo._album, (error, album) => {
    // find album and remove photo
  });
});

这篇关于猫鼬模型是另一个模型的后挂钩内的空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:52