Как бороться с родительскими и дочерними схемами мангуста, которые имеют циклические зависимости?

Моя родительская модель и дочерняя модель require друг друга, поэтому у меня есть циклические зависимости.

Из-за циклической зависимости const Parent = require("./Parent"); не импортирует Parent в Child.js. И поэтому, когда я звоню child.remove(), я получаю TypeError: Parent.findById is not a function.

Причина, по которой они ссылаются друг на друга, заключается в том, что при удалении дочернего элемента его идентификатор ссылки удаляется из родительского. И когда родитель удаляется, мне также нужно удалить всех его дочерних элементов из базы данных. Это делается в pre hooks схем.

Как я могу позаботиться об удалении дочерней ссылки в ее родительском и родительских дочерних элементах без этой циклической зависимости, вызывающей ошибки?

Родительский.js

const mongoose = require('mongoose');
const Child = require('./Child');

const parentSchema = new mongoose.Schema(
  {
    name: String,
    childrenIds: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'child',
      },
    ],
  },
  { timestamps: { createdAt: 'created_at' } }
);

parentSchema.pre('remove', async function (next) {
  await Child.deleteMany({ _id: { $in: this.childrenIds } });
  next();
});

const Parent = mongoose.model('Parent', parentSchema);
module.exports = Parent;

Child.js:

const mongoose = require('mongoose');
const Child = require('./Child');

const parentSchema = new mongoose.Schema(
  {
    name: String,
    childrenIds: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'child',
      },
    ],
  },
  { timestamps: { createdAt: 'created_at' } }
);

parentSchema.pre('remove', async function (next) {
  await Child.deleteMany({ _id: { $in: this.childrenIds } });
  next();
});

const Parent = mongoose.model('Parent', parentSchema);
module.exports = Parent;

app.js:

const Parent = require('./models/Parent');
const Child = require('./models/Child');
const mongoose = require('mongoose');

mongoose
  .connect('mongodb://localhost/circularDep_db', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: true,
  })
  .then(() => console.log('Successfully connect to MongoDB.'))
  .catch((err) => console.error('Connection error', err));

const addChild = async (parent, child) => {
  child.parentId = parent._id;
  await child.save();
  parent.childrenIds.push(child);
  await parent.save();
};

async function run() {
  const parent = await Parent.create({ name: 'Caryn' });
  const child = await Child.create({ name: 'Dashie' });
  const child2 = await Child.create({ name: 'Chappie' });
  await addChild(parent, child);
  await addChild(parent, child2);
  await child.remove(); // throws a type error
  await parent.remove();
}

run();

person Dashiell Rose Bark-Huss    schedule 22.09.2020    source источник
comment
а) поместите их в один и тот же файл, если они настолько переплетены б) не используйте module.exports, а exports.Parent = … или в) лениво выполните require(…) внутри прехука   -  person Bergi    schedule 22.09.2020